如何将格式字符串选项从用户传递到我的组件?

时间:2018-03-09 15:38:35

标签: rust

我想让用户决定我的struct的格式,然后将其传递给它下面的struct。

例如:

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)
    }
}

我想让它像

一样工作
let c = Coordinates { x: 10, y: 20 };

println!("{}", c);
// => Coordinates(x: 10, y: 20)

println!("{:010x}, c");
// => Coordinates(x: 000000000a, y: 0000000014)

我希望"{:010x}"直接传递到"Coordinates(x: {here}, y: {and here})"。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:7)

您可以编写self.x.fmt(f)将呼叫转发给其内部成员,重复使用相同的格式化程序。

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)"
    );
}