Rust格式化打印
1.2 Rust格式化打印
打印是通過一係列在標準定義std::fmt其中一些宏處理包括:
-
format!
: 寫格式化的文本到字符串 -
print!
: 類似於format!
但文本打印到控製台上。 -
println!
: 類似於print!
但追加一個換行符。
以相同的方式解析全部文本。加號是正確的格式將在編譯時進行檢查。
fn main() { // In general, the `{}` will be automatically replaced with any // arguments. These will be stringified. println!("{} days", 31); // Without a suffix, 31 becomes an i32. You can change what type 31 is, // with a suffix. // There are various optional patterns this works with. Positional // arguments can be used. println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"); // As can named arguments. println!("{subject} {verb} {predicate}", predicate="over the lazy dog", subject="the quick brown fox", verb="jumps"); // Special formatting can be specified after a `:`. println!("{} of {:b} people know binary, the other half don't", 1, 2); // It will even check to make sure the correct number of arguments are // used. println!("My name is {0}, {1} {0}", "Bond"); // FIXME ^ Add the missing argument: "James" // Create a structure which contains an `i32`. Name it `Structure`. struct Structure(i32); // However, custom types such as this structure require more complicated // handling. This will not work. println!("This struct `{}` won't print...", Structure(3)); // FIXME ^ Comment out this line. }
std::fmt 包括多個 traits 支配文本的顯示。 兩個重要的基本形式如下:
-
fmt::Debug
: 使用{:?}
標記。格式文本用於調試的目的。 -
fmt::Display
: 使用{}
標記。在一個更優雅的,用戶友好的方式設置文本格式。
這裡, fmt::Display
被使用,因為std庫提供這些類型。 打印文本自定義類型,需要更多的步驟。