Rust格式化输出:println、format格式化参数详解

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值