【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:?}"));
}
相关推荐
chillxiaohan5 分钟前
GO学习踩坑记录
开发语言·学习·golang
He BianGu18 分钟前
【笔记】DebuggerDisplay、DebuggerBrowsable 及其相关“系列”特性的系统性说明
笔记·c#
其美杰布-富贵-李18 分钟前
OpenCalphad 学习笔记
笔记·学习·热力学计算
hkNaruto19 分钟前
【AI】AI学习笔记:直接使用Python+BM25算法实现RAG的可行性以及实用价值
人工智能·笔记·学习
testpassportcn26 分钟前
Dell D-MSS-DS-23 認證介紹|Dell Data Scientist 考試全解析與高效備考指南
网络·学习·改行学it
Lv117700827 分钟前
WinForm常用控件功能介绍及使用模板
笔记·c#·visual studio·winform
MarkHD35 分钟前
智能体在车联网中的应用:第52天 大语言模型作为高级规划器或世界模型:重塑自动驾驶的感知与决策
学习·安全
week_泽36 分钟前
第7课:管理长期记忆的关键架构决策 - 学习笔记_7
java·笔记·学习·ai agent
koo36437 分钟前
pytorch深度学习笔记15
pytorch·笔记·深度学习
FAFU_kyp1 小时前
Rust 所有权(Ownership)学习
开发语言·学习·rust