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

标签 rust string-formatting traits

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

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) 以便能够以所需的精度进行打印。

最佳答案

如评论中所述,使用 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)
    }
}

关于rust - 如何在实现 Debug 时访问指定的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47397641/

相关文章:

python - 如何将 f-string 与变量一起使用,而不是与字符串文字一起使用?

javascript - javascript 中的特性

scala - 使用密封特征作为 map 的键

rust - 结构的生命周期边界如何在 Rust 中工作?

rust - 如何启用?替代 unwrap in rust 的功能?

rust - 什么是有效字符以及如何在clap.rs参数中转义?

python-3.x - 如何在 f 字符串中使用 lambda 函数并有条件地返回值?

c# - 使用 C# System.Drawing/Drawstring 将图像大小调整为图像中的文本

rust - 在 Rust 中匹配字符串元组

rust - 特征中的生命周期