【Rust学习笔记】ToString

Rust 中的 ToString 方法

rust中,要实现一个Value的toString方法,需要实现 std::fmt::Display,而不是直接实现 std::string::ToString。

参考:ToString trait

rust 复制代码
struct Point {
    x: i32,
    y: i32,
}

impl std::fmt::Display for Point {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

fn main() {
    let p = Point {
        x: 1,
        y: 2,
    };

    assert_eq!("(1, 2)", p.to_string());
    assert_eq!("p: (1, 2)", format!("p: {}", p));
}

std::fmt::Display 和 std::fmt::Debug 的区别

  1. Display 是面向用户的一个trait,不能使用 derive
  2. Debug 是面向程序员调试的一个trait,可以使用 derive,并且derive的Debug是不稳定的,可能随着Rust版本变化。
rust 复制代码
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point {
        x: 1,
        y: 2,
    };

    assert_eq!("Point { x: 1, y: 2 }", format!("{:?}", p));
    assert_eq!("Point { x: 1, y: 2 }", format!("{p:?}"));
    assert_eq!("pretty: Point {
    x: 1,
    y: 2,
}", format!("pretty: {:#?}", p));
    assert_eq!("pretty: Point {
    x: 1,
    y: 2,
}", format!("pretty: {p:#?}"));
}

派生的Debug

一个struct 实现了derive 的 Debug,则其成员也需要实现 Debug。

rust 复制代码
struct Point {
    x: i32,
    y: i32,
}

impl Display for Point {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

impl std::fmt::Debug for Point {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

#[derive(Debug)]
struct Line {
    from: Point,
    to: Point,
}

fn main() {
    let l = Line {
        from: Point { x: 0, y: 0 },
        to: Point { x: 1, y: 1 },
    };

    assert_eq!("l: Line { from: (0, 0), to: (1, 1) }", format!("l: {l:?}"));
}
相关推荐
2501_945318498 小时前
备考方案:针对数据分析师的知识结构,制定攻克赛一认证的最优学习路径
学习·百度
2301_792674869 小时前
java学习day29(juc)
java·开发语言·学习
qq_5710993511 小时前
学习周报四十
学习
Flittly11 小时前
【SpringAIAlibaba新手村系列】(16)调用百度 MCP 服务
java·笔记·spring·ai·springboot
瑶光守护者12 小时前
【一文读懂】OpenClaw系统架构分析:自主人工智能智能体的范式迁移与技术底座分析
人工智能·笔记·学习·系统架构·边缘计算·openclaw
爱分享的阿Q12 小时前
RustWebAssembly商用元年从实验到生产完整迁移指南
rust·web·wasm
锦瑟弦音13 小时前
金蝶二开笔记&&setCancelMessage
笔记
炽烈小老头13 小时前
【每天学习一点算法 2026/04/13】两数相除
学习·算法
大卫小东(Sheldon)13 小时前
Rudist v0.5.1 发布:AI 驱动的 Redis 客户端,更快、更直观
rust·rudist
_李小白13 小时前
【OSG学习笔记】Day 45: osg::Camera::DrawCallback (抓取图片)
笔记·学习