Rust的format!
、println!
宏实现了灵活而强大的格式化方式。接下来,对一些常用到的写法进行总结。
基本姿势
#[test]
fn test_format() {
println!("{},{}", 1, 2); // 基本方式,打印实现了Display trait的类型
println!("{:?}", "test"); // 打印实现了Debug trait的类型
// (
// "1. t1",
// "2. t2",
// )
println!("{:#?}", ("1. t1", "2. t2")); // 带换行和缩进的Debug打印
// 直接捕获上下文中的变量
let x = 16;
let y = 32;
println!("({x}, {y})");//(16, 32)
}
打印2/8/16进制
//二进制
println!("0b{:b}", 0b11_01); // 0b1101
println!("{:#b}", 0b11_01); // 0b1101
//八进制
println!("0o{:o}", 10); // 0o12
println!("{:#o}", 10); // 0o12
//十六进制小写
println!("0x{:x}", 0xFF); //0xff
println!("{:#x}", 0xFF); //0xff
//十六进制大写
println!("0x{:X}", 0xFF); // 0xFF
println!("{:#X}", 0xFF); // 0xFF
打印内存地址(指针或引用)
println!("{:p}", &100); //0x7ff7794869c4
科学计数
println!("{:e}", 1000f32); // 1e3,科学计数(小写)
println!("{:E}", 1000f64); // 1E3,科学计数(大写)
使用参数索引和命名参数
// 使用参数索引
println!("{0} {1} {1}", "p", "q"); //p q q
// 使用命名参数
println!("{a} {b} {b}", a = "1", b = "2"); //1 2 2
padding和对齐
> 右对齐,默认方式
^ 居中对齐
< 左对齐
// 右对齐,不足左边补空格
println!("|{:6}|", 21);//| 21|
println!("|{:>6}|", 21);//| 21|
// 右对齐,不足左边补0
println!("{:06}", 21);//000021
println!("{:>06}", 21);//000021
println!("{:0>6}", 21);//000021
// 右对齐,左边补-
println!("{:->6}", 21);//----21
// 居中对齐
println!("|{:^6}|", 21);//| 21 |
// 左对齐,右边补-
println!("|{:-<6}|", 21);//|21----|
相关的宏
支持格式化参数相关的宏:
format!
write! // first argument is a &mut io::Write, the destination
writeln! // same as write but appends a newline
print! // the format string is printed to the standard output
println! // same as print but appends a newline
eprint! // the format string is printed to the standard error
eprintln! // same as eprint but appends a newline
format_args! // described below.
参考标准库文档
更多详情,参考rust标准库文档:https://doc.rust-lang.org/std/fmt/index.html