【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:?}"));
}
相关推荐
我命由我1234521 分钟前
Photoshop - Ps还原和历史记录
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
我命由我1234537 分钟前
Photoshop - Ps工作界面
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
梅羽落42 分钟前
XPath笔记
笔记
桂花很香,旭很美1 小时前
Anthropic Agent 工程实战笔记(六)安全与生产
笔记·架构·agent
ps酷教程1 小时前
spring-retry学习 (2) -图解源码
学习
2501_943695331 小时前
大专市场调查与统计分析专业,怎么学习市场调研问卷的设计?
人工智能·学习
sponge'1 小时前
opencv学习笔记14:transformer
笔记·学习·transformer
xhyu612 小时前
【学习笔记】推荐系统 (4.召回:Deep Retrieval、其他召回通道、曝光过滤)
笔记·学习
CS生2 小时前
Rust环境准备
开发语言·后端·rust
小帅学编程3 小时前
Python学习
开发语言·python·学习