std
format print
打印由 std::fmt 中定义的一系列 macros 处理,其中一些包括:
| name | description |
|---|---|
| format! | 将格式化文本写入 String |
| print! | 与 format! 相同,但文本被打印到控制台(io::stdout)。 |
| println! | 与 print! 相同,但附加了换行符。 |
| eprint! | 与 print! 相同,但文本被打印到标准错误 (io::stderr)。 |
| eprintln! | 与 eprint! 相同,但附加了换行符。s |
fn main() {
println!("{} days", 31);
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jumps over");
println!("Base 10: {}", 69420); // 69420
println!("Base 2 (binary): {:b}", 69420); // 10000111100101100
println!("Base 8 (octal): {:o}", 69420); // 207454
println!("Base 16 (hexadecimal): {:x}", 69420); // 10f2c
println!("{number:>5}", number=1);// output " 1".
println!("{number:0>5}", number=1); // 00001
println!("{number:0<5}", number=1); // 10000
println!("{number:0>width$}", number=1, width=5); // 00001
// For rust 1.58 and above, you can directly capture the argument from a
// surrounding variable. Just like the above, this will output
// " 1", 4 white spaces and a "1".
let number: f64 = 1.0;
let width: usize = 5;
println!("{number:>width$}");
}
std::fmt 包含许多控制文本显示的 traits 。下面列出了两个重要的基本形式:
- fmt::Debug :使用
{:?}标记。设置文本格式以用于调试目的。 - fmt::Display :使用
{}标记。以更优雅、用户友好的方式设置文本格式。
在这里,我们使用 fmt::Display 因为 std 库提供了这些类型的实现。要打印自定义类型的文本,需要更多步骤。
实现 fmt::Display 特征会自动实现 ToString 特征,它允许我们将类型转换为 String 。
第 43 行中, #[allow(dead_code)] 是一个属性,仅适用于其后的模块。