I want to have the user decide the formatting of my struct, and just pass it to the struct underneath it.
For example:
struct Coordinates {
x: i64,
y: i64,
}
impl fmt::Display for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: {}, y: {})", self.x, self.y)
}
}
impl fmt::LowerHex for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: {:x}, y: {:x})", self.x, self.y)
}
}
I want this to work like
let c = Coordinates { x: 10, y: 20 };
println!("{}", c);
// => Coordinates(x: 10, y: 20)
println!("{:010x}, c");
// => Coordinates(x: 000000000a, y: 0000000014)
I want to have "{:010x}"
passed directly into "Coordinates(x: {here}, y: {and here})"
. How can I achieve this?
You could write self.x.fmt(f)
to forward the call to its inner members reusing the same formatter.
use std::fmt;
struct Coordinates {
x: i64,
y: i64,
}
impl fmt::Display for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: ")?;
self.x.fmt(f)?;
write!(f, ", y: ")?;
self.y.fmt(f)?;
write!(f, ")")?;
Ok(())
}
}
impl fmt::LowerHex for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: ")?;
self.x.fmt(f)?;
write!(f, ", y: ")?;
self.y.fmt(f)?;
write!(f, ")")?;
Ok(())
}
}
fn main() {
let c = Coordinates { x: 10, y: 20 };
assert_eq!(format!("{}", c), "Coordinates(x: 10, y: 20)");
assert_eq!(
format!("{:010x}", c),
"Coordinates(x: 000000000a, y: 0000000014)"
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With