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"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章