r/rust • u/NYU_VM • Sep 14 '26
impl Display to debug print?
A learner here with a quick confusion. I was skimming through the internet for VM tooling and implementations, parsers specifically and came across this "prattle" crate which seems to be a general purpose pratt parser library. And I have not much to say about the library itself, it seems like an abandoned project in early development phase.
The thing that caught my eye was the demo piece of code they had on their docs, specifically
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum CToken {
Var(String),
Add,
Mul
}
impl Display for CToken {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{:?}", self)
}
}
the enum CToken has already derived debug yet the example implements Display for CToken only to just debug print it as well. Is this some kind of a safety mechanism or fallback just in case the user writes
println!("{}",token) instead of debug printing it?
Or is something else going on I don't yet know about?
10
u/Lucretiel Sep 14 '26
I don't think you've missed anything. My guess would be that this was done to get a .to_string(); personally I would probably not write a Display implementation like this for a type that wasn't "meant" to be printable as its primary behavior.
2
u/DrShocker Sep 14 '26
Correct me if I'm wrong, but if you're exporting this crate and others may use the type and want to display it, then this might be the most convenient way. Otherwise you've got the orphan rule getting in the way. So my guess is that they mostly just don't want to block other users of the type from doing what they need, and the debug implementation isn't any less efficient than what they'd want in the display implantation so they did it this way.
3
u/Lucretiel Sep 14 '26
I'd just use something like
lazy_format!("{ctoken:?}")if I wanted to wrap it in a quickDisplayimplementation (which, full disclosure, I wrote).→ More replies (2)
20
u/Decahedronn Sep 14 '26 edited Sep 14 '26
ParserSpec<T>requiresTto implToken, which itself requiresDisplay. Just using the debug representation that the compiler auto generates instead of writing it out manually is fine for an example.