I'm implementing a file format parser, and I have an enum
which reflects the general chunks allowed in the file specification. Something like:
#[derive(Debug)]
pub enum FileChunk {
FileVersionChunk { major: u16, minor: u16 },
AuthorChunk { name: String },
// many many more variants following the specs...
DataChunk { data: Vec<u8> },
}
For debugging purposes I want to implement the Debug
trait for this enum. The standard implementation #[derive(Debug)]
is super useful for that purpose, but has one issue: Some variants like the DataChunk
contain huge data elements, which I want to abbreviate in the debugging output. How can this be accomplished?
I'm new to Rust -- naively I would see two approaches:
- Keep the default
#[derive(Debug)]
implementation but somehow override that a certain variant should have a special implementation. I couldn't figure out though, if something like that is possible in Rust. - Remove the default
#[derive(Debug)]
implementation, and implement the trait explicitly. In this case I'm trying to find a solution that allows to only implement the specific variantDataChunk
manually, but somehow fall back to a default implementation for all other cases1. However I can't figure out how to make such a fallback work. I tried the following as a test, but that leads to an infinite recursion, because thewrite!
expression basically callsfmt
again.
impl Debug for FileChunk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
write!(f, "{:#?}", self)
}
}
1 the specs require ~30 variants, so manually implementing all of them would be very tedious, and there are further enums where I have the same problem.