【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:?}"));
}
相关推荐
wheelmouse77883 分钟前
Python 装饰器函数(decoratots) 学习笔记
笔记·python·学习
电饭叔9 分钟前
案例证明法--内容学习
学习
li星野16 分钟前
OpenCV4X学习-轮廓检测、水印、凸缺陷检测、数字水印
学习
yang0111100116 分钟前
论文总结 HVI: A New Color Space for Low-light Image Enhancement
图像处理·人工智能·学习·计算机视觉
LYS_061817 分钟前
寒假学习(2)(C语言2+模数电2)
c语言·学习·算法
shanghaichutai25 分钟前
Valosin (porcine) (Peptide VQY (porcine)) ;VQYPVEHPDKFLKFGMTPSKGVLFFY
笔记
listhi52027 分钟前
压缩感知信号重构的块稀疏贝叶斯学习(BSBL)算法:原理、实现与应用
学习·算法·重构
三伏52231 分钟前
Cortex-M3权威指南Cn第三章——笔记
笔记·cortex-m3
方安乐36 分钟前
react笔记之useCallback
前端·笔记·react.js
漏刻有时1 小时前
微信小程序学习实录15:微信小程序基于百度云人脸识别的刷脸打卡开发方案
学习·微信小程序·百度云