通过例子学习Rust

2 格式化输出

println! 不仅仅是向控制台输出,还负责格式化文本和把其他非文本值转换为文本,并在编译期间执行格式检查。

fn main() { // `print!` is like `println!` but it doesn't add a newline at the end print!("January has "); // `{}` are placeholders for arguments that will be stringified println!("{} days", 31i); // The `i` suffix indicates the compiler that this literal has type: signed // pointer size integer, see next chapter for more details // The positional arguments can be reused along the template println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"); // Named arguments can also be used println!("{subject} {verb} {predicate}", predicate="over the lazy dog", subject="the quick brown fox", verb="jumps"); // Special formatting can be specified in the placeholder after a `:` println!("{} of {:b} people know binary, the other half don't", 1i, 2i); // Error! You are missing an argument println!("My name is {0}, {1} {0}", "Bond"); // FIXME ^ Add the missing argument: "James" }

std::fmt 文档中能找到有关格式化文本的更多信息。