【Rust】格式化输出-display

环境

  • Rust 1.55.0
  • VSCode 1.59.1

概念

Display 输出使用 {} 来进行打印,Display 主要是面向用户的输出。
如果要实现 display 输出,需要实现 std::fmt::Display 这个 trait。

trait 可以先简单理解为其它编程语言中的接口

示例

display 输出

fn main() {
    let a = "name";
    let b = 44;

    println!("{}, {}", a, b);
}

手动实现

fn main() {
    use std::fmt;

    struct Point {
        x: i32,
        y: i32,
    }

    impl fmt::Display for Point {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "({}, {})", self.x, self.y)
        }
    }

    let origin = Point { x: 0, y: 0 };
    println!("{}", origin);
}

练习

fn main() {
    use std::fmt;

    struct Point2D {
        x: f64,
        y: f64,
    }

    impl fmt::Display for Point2D {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "Display: {} + {}i", self.x, self.y)
        }
    }

    impl fmt::Debug for Point2D {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "Debug: Complex {{ real: {}, imag: {} }}", self.x, self.y)
        }
    }

    let origin = Point2D { x: 3.3, y: 7.2 };
    println!("{}", origin);
    println!("{:?}", origin);
}

总结

介绍了使用 Display 进行格式化输出。

附录

posted @   jiangbo4444  阅读(814)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2019-11-30 spring-boot 环境搭建(一)
点击右上角即可分享
微信分享提示