println 的格式样式有什么区别? [英] What is the difference between println's format styles?
问题描述
很抱歉问这么简单的问题……一天前,我开始学习 Rust 并尝试了 println!
方法.
I'm so sorry to ask such a simple question... A day ago, I started learning Rust and tried the println!
method.
fn main() {
println!("Hello {}!", "world");
}
-> Hello world!
然后,我发现了其他格式样式:{}, {:}, {:?}, {?}
, ...
And then, I found other format styles: {}, {:}, {:?}, {?}
, ...
我知道 {}
是 String
,但我不了解其他格式样式.这些风格有什么不同?我认为 {:?}
是数组或向量.正确吗?
I know that {}
is instead String
, but I don't understand the other format style. How do those styles differ from each other? I think {:?}
is array or vector. Is it correct?
请用示例代码解释这些格式样式:(
Please explain these format style with sample code :(
推荐答案
为了彻底,std::fmt
格式化语法由两部分组成:
For thoroughness, the std::fmt
formatting syntax is composed of two parts:
{<position-or-name>:<format>}
哪里:
可以是参数位置:println!("Hello {0}!"
, "world");`,注意在编译时检查它
也可以是名字:println!("Hello {arg}!", arg = "world");
是 其中之一以下格式,其中每种格式都需要参数来实现特定的特征,在编译时检查
<position-or-name>
can be the argument position:println!("Hello {0}!"
, "world");`, note that it is checked at compile-time<position-or-name>
can also be a name:println!("Hello {arg}!", arg = "world");
<format>
is one of the following formats, where each format requires the argument to implement a specific trait, checked at compile-time
默认情况下,在没有位置、名称或格式的情况下,选择与 {}
的索引匹配的参数并使用 Display
特征.然而却有各种各样的特点!来自上面的链接:
The default, in the absence of position, name or format, is to pick the argument matching the index of {}
and to use the Display
trait. There are however various traits! From the link above:
- 没有 ⇒ 显示
?
⇒ 调试o
⇒ 八进制x
⇒ 下十六进制X
⇒ UpperHexp
⇒ 指针b
⇒ 二进制e
⇒ LowerExpE
⇒ UpperExp
- nothing ⇒ Display
?
⇒ Debugo
⇒ Octalx
⇒ LowerHexX
⇒ UpperHexp
⇒ Pointerb
⇒ Binarye
⇒ LowerExpE
⇒ UpperExp
如有必要,将来可以添加新特征.
and if necessary new traits could be added in the future.
这篇关于println 的格式样式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!