Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass down format string options from the user to my components?

Tags:

rust

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?

like image 709
Todoroki Avatar asked Mar 09 '18 15:03

Todoroki


1 Answers

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)"
    );
}
like image 182
kennytm Avatar answered Nov 12 '22 19:11

kennytm