【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:?}"));
}
相关推荐
蒙奇D索大31 分钟前
【算法】 递归实战应用:从暴力迭代到快速幂的优化之路
笔记·考研·算法·改行学it
9ilk41 分钟前
【仿RabbitMQ的发布订阅式消息队列】 ---- 功能测试联调
linux·服务器·c++·分布式·学习·rabbitmq
('-')1 小时前
《从根上理解MySQL》第一章学习笔记
笔记·学习·mysql
d111111111d1 小时前
STM32外设学习-串口发送数据-接收数据(笔记)
笔记·stm32·学习
Elias不吃糖1 小时前
eventfd 初认识Reactor/多线程服务器的关键唤醒机制
linux·服务器·c++·学习
宋辰月2 小时前
学习react第三天
前端·学习·react.js
昊喵喵博士3 小时前
直接用 JavaScript 给输入框赋值,Vue 页面input只是纯展示 并 没有触发 vue 的v-model 赋值
笔记
月下倩影时3 小时前
视觉学习篇——机器学习模型评价指标
人工智能·学习·机器学习
重启编程之路3 小时前
python 基础学习socket -UDP编程
python·网络协议·学习·udp
大卫小东(Sheldon)3 小时前
革命你的 Git 提交消息 - GIM 1.8.0 发布了!
ai·rust·管理