【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:?}"));
}
相关推荐
my_power5201 分钟前
大模型概述学习笔记
笔记·学习
心中有国也有家3 分钟前
Flutter 鸿蒙编译与构建流程深度解析
学习·flutter·华为·harmonyos
敲不会代码也学不会英语8 分钟前
【AI学习之旅02】AI全景图:一张图看懂AI生态——机器学习/深度学习/大模型关系与术语扫盲
人工智能·学习·机器学习
LiaoWL12331 分钟前
【SpringCloud合集-02】Spring Cloud LoadBalancer 负载均衡器学习笔记
学习·spring cloud·负载均衡
YUS云生35 分钟前
Python学习笔记·第28天:Git入门——版本控制与基础操作
笔记·python·学习
Yang_jie_0337 分钟前
笔记:数据结构(链表)
数据结构·笔记·链表
xiaoyuchidayuma38 分钟前
【# 电压极限圆、电流极限圆、MTPA曲线、最大功率曲线的关系】
笔记·学习
程序员爱钓鱼41 分钟前
第一个 Rust 程序 Hello World
后端·rust
五哈俱乐部1 小时前
TCHouse-C分布式表创建指南
笔记
问君能有几多愁~9 小时前
C++ 数据结构复习笔记
数据结构·c++·笔记