【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:?}"));
}
相关推荐
Coisinilove31 分钟前
MATLAB学习笔记——第三章
笔记·学习·matlab
小乔的编程内容分享站32 分钟前
C语言笔记一维&二维数组
c语言·笔记
非凡ghost1 小时前
Ookla Speedtest安卓版(网速测试工具)
android·windows·学习·智能手机·软件需求
近津薪荼2 小时前
dfs专题7—— 全排列
c++·学习·算法·深度优先
火红色祥云2 小时前
深度学习入门:基于Python的理论与实现笔记
笔记·python·深度学习
Aliex_git2 小时前
gzip 压缩实践笔记
前端·网络·笔记·学习
菡萏如佳人2 小时前
AI时代学习新范式—认知供应链模式(附OpenClaw四步拆解)
人工智能·学习
liuchangng2 小时前
BMAD-METHOD实战笔记_20260213112550
笔记
2501_901147833 小时前
打家劫舍问题的动态规划解法与性能优化笔记
笔记·算法·动态规划
像豆芽一样优秀3 小时前
Easy-Vibe Task02学习笔记
笔记·学习