【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:?}"));
}
相关推荐
Rust语言中文社区13 小时前
【Rust日报】 丰田“先锋”选择了 Rust
开发语言·后端·rust
邹小邹-AI13 小时前
Rust + 前端:下一个十年的“王炸组合”
开发语言·前端·rust
二川bro14 小时前
多模态AI开发:Python实现跨模态学习
人工智能·python·学习
love530love14 小时前
【笔记】ComfUI RIFEInterpolation 节点缺失问题(cupy CUDA 安装)解决方案
人工智能·windows·笔记·python·插件·comfyui
石像鬼₧魂石14 小时前
Netcat,网络瑞士军刀(新手学习备用)
学习
愚戏师14 小时前
MySQL 数据导出
数据库·笔记·mysql
摇滚侠15 小时前
2025最新 SpringCloud 教程,教程简介,笔记01
笔记·spring cloud
todoitbo15 小时前
基于 DevUI MateChat 搭建前端编程学习智能助手:从痛点到解决方案
前端·学习·ai·状态模式·devui·matechat
芳草萋萋鹦鹉洲哦16 小时前
【tauri+rust】App会加载白屏,有时显示在左上角显示一小块,如何优化
开发语言·后端·rust