【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:?}"));
}
相关推荐
好望角雾眠3 分钟前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
艾伦~耶格尔6 分钟前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
星仔编程18 分钟前
python学习DAY46打卡
学习
大霞上仙1 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
yatingliu20193 小时前
HiveQL | 个人学习笔记
hive·笔记·sql·学习
郭庆汝3 小时前
CMake概述用法详细笔记
笔记
武当豆豆3 小时前
C++编程学习(第25天)
开发语言·c++·学习
张人玉3 小时前
XML 序列化与操作详解笔记
xml·前端·笔记
风和日丽 随波逐流3 小时前
java17学习笔记-Deprecate the Applet API for Removal
笔记·学习
淮北也生橘123 小时前
Linux的ALSA音频框架学习笔记
linux·笔记·学习