【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:?}"));
}
相关推荐
Hello_Embed17 小时前
嵌入式上位机开发入门(二十八):JSON 与 JsonRPC 入门
网络·笔记·网络协议·tcp/ip·嵌入式
代码羊羊17 小时前
Rust-特征trait和特征对象
服务器·网络·rust
U盘失踪了17 小时前
Playwright codegen脚本录制
笔记
Joseph Cooper18 小时前
STM32MP157 Linux驱动学习笔记(一):驱动基础与设备模型入门(同步互斥/LCD/I2C/Input)
linux·stm32·学习
Joseph Cooper18 小时前
STM32MP157 Linux驱动学习笔记(二):硬件资源地基(Pinctrl/GPIO/Interrupt)
linux·stm32·学习
xieliyu.18 小时前
Java手搓数据结构:从零模拟实现单向无头非循环链表
java·数据结构·学习·链表
conti12318 小时前
水题记录2.4
c++·笔记·题解
圆山猫18 小时前
[AI] [Linux] 教我用rust写一个GPIO驱动
linux·rust
y = xⁿ18 小时前
MySQL学习日记:关于MVCC及一些八股总结
数据库·学习·mysql
做cv的小昊18 小时前
【TJU】研究生应用统计学课程笔记(4)——第二章 参数估计(2.1 矩估计和极大似然估计、2.2估计量的优良性原则)
人工智能·笔记·考研·数学建模·数据分析·excel·概率论