i have code like this, with the idea of adding a lot more code in the future:
use std::fmt;
enum Value {
Int(u32),
Str(String),
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use Value::*;
match &self {
Int(x) => {
write!(f, "{}", x)
}
Str(x) => {
write!(f, "{}", x)
}
}
}
}
i want to get rid of the repeated write!
calls, preferably without using a complex macro.
my first idea was something like this:
use std::fmt;
enum Value {
Int(u32),
Str(String),
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use Value::*;
match &self {
Int(x) | Str(x) => {
write!(f, "{}", x)
}
}
}
}
where x
is coerced into &dyn Display
within the match arm. this might be possible with type ascription, but that has been gone for some time.
macros don't even help that much, as they can't expand to match arms.
also, i want to be add some cases that are more complex.