gpt4 book ai didi

rust - 有没有办法在 Rust 中用 "0x"右对齐十六进制数?

转载 作者:行者123 更新时间:2023-11-29 08:00:45 25 4
gpt4 key购买 nike

我正在尝试用 Rust 打印这样的东西:

Base:       0x40, length: 900
Base: 0x5500, length: 301

现在我有:

println!("Base: {:>width$x}, length: {}", 67106, 54, width=10);
Base:      10622, length: 54

有没有办法让 Rust 包含“0x”前缀?这两个不编译:

println!("Base: {:>width#$x}, length: {}", 67106, 54, width=10);
println!("Base: {:>width$#x}, length: {}", 67106, 54, width=10);
error: invalid format string: expected `'}'`, found `'#'`
--> src/main.rs:2:29
|
2 | println!("Base: {:>width#$x}, length: {}", 67106, 54, width=10);
| - ^ expected `}` in format string
| |
| because of this opening brace
|
= note: if you intended to print `{`, you can escape it using `{{`

error: invalid format string: expected `'}'`, found `'#'`
--> src/main.rs:3:30
|
3 | println!("Base: {:>width$#x}, length: {}", 67106, 54, width=10);
| - ^ expected `}` in format string
| |
| because of this opening brace
|
= note: if you intended to print `{`, you can escape it using `{{`

我最好的是:

println!("Base: 0x{:0>8x}, length: {}", 67106, 54);
Base: 0x00010622, length: 54

这可能没问题,但我很好奇是否有办法做到这一点。另外,我想也许这会奏效,但没有这样的运气:

println!("Base: {:>10}, length: {}", format_args!("{:#x}", 67106), 54);
Base: 0x10622, length: 54

最佳答案

println!("Base: {:>#10x}, length: {}", 0x40, 900);

您需要在宽度前加上# 来设置替代形式。查看std::fmt syntax格式的解释。

width 作为参数传递,将是:

println!("Base: {:>#width$x}, length: {}", 67106, 301, width=10);

关于rust - 有没有办法在 Rust 中用 "0x"右对齐十六进制数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58565226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com