I have an enum:
pub enum BoxColour {
Red,
Blue,
}
I not only want to get this value as a string, but I want the value to be converted to lower case.
This works:
impl Display for BoxColour {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(match self {
BoxColour::Red => "red",
BoxColour::Blue => "blue",
})?;
Ok(())
}
}
When the list of colours grows, this list would need to be updated.
If I use the write! macro, it does not seem possible to manipulate the result because write! returns an instance of () instead of a String:
impl Display for BoxColour {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{:?}", self)
}
}
This suggests that this is working through side effects and maybe we could hack the same place in memory the value is going, but even if that is possible, it probably isn't a good idea...
write!returns an instance of()— it does not. It returns afmt::Result, as shown by the return type offmt.fmt::Resultis atypeforResult<(), fmt::Error>.Displayformat will be. It seems like you've linked to a suitable solution.Resultis()instead ofStringor something I might know how to work with. I sawstrum, but couldn't get that to work either, but that's a question for a different day.