如何在实现Debug时访问指定的精度?

时间:2017-11-20 17:21:24

标签: rust string-formatting traits

我有一个简单的结构来保持f64 s的间隔:

pub struct Interval {
    pub min: f64,
    pub max: f64
}

此代码以硬编码3个小数位打印:

impl fmt::Debug for Interval {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{:.3?} {:.3?}]", self.min, self.max)
    }
}

我想支持println!("{:.6}", my_interval)能够以所需的精度打印。

1 个答案:

答案 0 :(得分:1)

如评论中所述,请使用Formatter::precision。已有一个例子in the documentation

impl fmt::Binary for Vector2D {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let magnitude = (self.x * self.x + self.y * self.y) as f64;
        let magnitude = magnitude.sqrt();

        // Respect the formatting flags by using the helper method
        // `pad_integral` on the Formatter object. See the method
        // documentation for details, and the function `pad` can be used
        // to pad strings.
        let decimals = f.precision().unwrap_or(3);
        let string = format!("{:.*}", decimals, magnitude);
        f.pad_integral(true, "", &string)
    }
}

对于你的情况:

impl fmt::Debug for Interval {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let precision = f.precision().unwrap_or(3);
        write!(f, "[{:.*?} {:.*?}]",  precision, self.min, precision, self.max)
    }
}