Rust中的格式化输出

格式化输出

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"
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值