You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust实现Display trait:复用调用者格式化规则及代码修改

Rust格式化问题解答

给定Rust程序如下,当前输出为1.23456:

use std::fmt;
struct Foo(f64);
impl fmt::Display for Foo {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", self.0)
    }
}
fn main() {
    println!("{:.2}", Foo(1.23456));
}

问题1解答

对fmt函数体做最简单的修改,直接在格式化字符串中指定精度即可:

write!(formatter, "{:.2}", self.0)

修改后程序运行会输出1.23。

问题2解答

有简便方法。Formatter实例已经包含了调用者设置的所有格式化选项(比如这里的.2精度),只需将内部的f64值直接交给Formatter处理,就能自动继承调用者的格式设置:

self.0.fmt(formatter)

这样修改后,不管调用者设置什么格式化参数(精度、宽度等),都会自动应用到self.0上,效果和直接执行println!("{:.2}", Foo(1.23456).0);完全一致。

内容的提问来源于stack exchange,提问作者carlo.milanesi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:02:44