如何在实现 Debug 时访问指定的精度?
How can I access the specified precision when implementing Debug?
我有一个简单的结构来保持 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
. There is already an example of this 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)
}
}
我有一个简单的结构来保持 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
. There is already an example of this 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)
}
}