打印是通过一系列在标准定义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库提供这些类型。 打印文本自定义类型,需要更多的步骤。