打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Rust中的格式化输出

Rust中的格式化输出

  • 格式化输出
    • println的使用
    • fmt::Debug的使用
    • fmt::Display的使用
    • 一个list类型的对象的自定义格式化输出
    • format的使用

格式化输出

rust中由一些宏(macro)负责输出,这些宏定义在std::fmt中,下面是一些常用的宏:

  • format!():向字符串中输出格式化字符串。
  • print()!:向标准输出打印字符串。
  • println()!:向标准输出打印字符串,同时会打印一个换行符。
  • eprint()!:向标准错误打印字符串。
  • eprintln()!:向标准错误打印字符串,同时也会打印一个换行符。

println的使用

  1. 使用{}通配符
println!("{} days", 31);
  1. 在{}中使用位置参数
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
  1. 在{}中使用命名参数
println!("{subject} {verb} {object}",
             object="the lazy dog",
             subject="the quick brown fox",
             verb="jumps over");
  1. 在{}中指定字符串格式化的方式
// 以二进制的格式打印数字
println!("{} of {:b} people know binary, the other half doesn't", 1, 2);
  1. 在{}中指定对齐方式以及对其宽度
// 右对齐宽度为6
println!("{number:>width$}", number=1, width=6);
// 使用字符0填充对齐的字符串
println!("{number:>0width$}", number=1, width=6);
  1. rust编译器会对格式化字符串的参数数量进行校验
// 由于参数数量不足,编译器会报错
println!("My name is {0}, {1} {0}", "Bond");
  1. println无法直接打印自定义类型
#[allow(dead_code)]
struct Structure(i32);
// 由于无法打印,编译器会报错
println!("This struct `{}` won't print...", Structure(3));    

fmt::Debug的使用

fmt::Debug的作用是以调试的目的打印字符串
fmt::Debug是Rust标准库已经定义好的,我们可以通过继承的方式,获得fmt::Debug的能力,在格式化中使用占位符{:?}。

#[derive(Debug)]
struct Structure(i32);
println!("Now {:?} will print!", Structure(3));

// 我们可以用稍微优雅的一点的方式打印
println!("{:#?}", Structure(3));

fmt::Display的使用

fmt::Display是一个用于自定义格式化输出的接口,如果需要按照我们自定义的格式进行格式化,我们只需要实现该接口就可以了

#[derive(Debug)]
struct MinMax(i64, i64);

// Implement `Display` for `MinMax`.
impl fmt::Display for MinMax {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Use `self.number` to refer to each positional data point.
        write!(f, "({}, {})", self.0, self.1)
    }
}
println!("Compare structures:");
// 自定义后,格式化占位符仍然使用{}
println!("Display: {}", minmax);
println!("Debug: {:?}", minmax);

一个list类型的对象的自定义格式化输出

use std::fmt; // Import the `fmt` module.

// Define a structure named `List` containing a `Vec`.
struct List(Vec<i32>);

impl fmt::Display for List {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Extract the value using tuple indexing,
        // and create a reference to `vec`.
        let vec = &self.0;

        write!(f, "[")?;

        // Iterate over `v` in `vec` while enumerating the iteration
        // count in `count`.
        for (count, v) in vec.iter().enumerate() {
            // For every element except the first, add a comma.
            // Use the ? operator, or try!, to return on errors.
            if count != 0 { write!(f, ", ")?; }
            write!(f, "{}", v)?;
        }

        // Close the opened bracket and return a fmt::Result value.
        write!(f, "]")
    }
}

fn main() {
    let v = List(vec![1, 2, 3]);
    println!("{}", v);
}

format的使用

  • 不做任何类型格式化原样输出
format!("{}", foo) -> "3735928559"
  • 以十六进制数的形式输出
format!("0x{:X}", foo) -> "0xDEADBEEF"
  • 以八进制的形式输出
format!("0o{:o}", foo) -> "0o33653337357"
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Rust基础学习笔记(零):复习基本知识
C语言、嵌入式中一些非常实用的宏技巧
排序,使用函数自定义排序,Panic,Defer
​半小时入门Rust,这是一篇Rust代码风暴
Rust 中支持扩容的动态数组
Rust学习笔记(5)- 定义和实例化
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服