Let's say I have a type Point whose coordinates I want to format in hex. I can do this:
use std::fmt;
struct Point {
x : i32,
y : i32
}
impl fmt::LowerHex for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(x=")?;
fmt::LowerHex::fmt(&self.x, f)?;
write!(f, ", y=")?;
fmt::LowerHex::fmt(&self.y, f)?;
write!(f, ")")
}
}
fn main() {
let p = Point { x : 100, y : 200 };
println!("Point is {0:x} or {0:#06x}", p);
}
That prints, as desired:
Point is (x=64, y=c8) or (x=0x0064, y=0x00c8)
Is this the best way of implementing LowerHex for Point?
And, if I want to them implement UpperHex as well, do I just have to basically duplicate all of this logic again?