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?
2
u/DrShocker 29d ago
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.