Using stringify!() for names of types

I was looking at this code in Rust today:

f.debug_tuple("Intersection").field(&answer).finish()

and I'm wordering if we couldn't use this as the standard style:

f.debug_tuple(stringify!(Intersection)).field(&answer).finish()

This is something I've adopted in my own code, because it feels marginally cleaner - Intersection is an ident, it's the name of a type (and if the type renames, so should we change this string in the Debug impl too).

Thoughts on this? I know it's a small thing and feels low-tech, but small things like this add up in refactoring. How do Rust's current refactoring tools handle renaming Intersection in this code?

3 Likes

Seems like it could unnecessarily increase compile times?

1 Like

You can actually take this a step further and get full rename safety now:

f.debug_tuple(std::any::type_name::<Self>()).field(&answer).finish()

(Not something I've actually used outside test code yet, just realised how nicely it might work when seeing this post).

3 Likes

Yeah, seems like the effect should be minimal though? Not more than any other added code.

Nice. The output would be messier that way, but you get a feature (that you might not want) - showing the generic parameters.

It might be noticable if you change the derive expansions of Debug -- @rust-timer should be able to find out.

+ the absolute path to the type.

I don't think we should change how derives expand. This is about open coded implementations, where the maintainability of using stringify matters.

yes this is not a wanted feature

2 Likes

I see; in that case I think @Nemo157's proposal is more maintainable.

It depends on the case? Sometimes an absolute path in debug logs can be more informative.

I observe that the docs for stringify! say:

Note that the expanded results of the input tokens may change in the future. You should be careful if you rely on the output.

(which seems a bit mealy-mouthed: surely either stability is guaranteed or it is not; "be careful" seems unhelpful.)

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.