gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:35:20 27 4
gpt4 key购买 nike

我有一个简单的结构来保持 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com