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: {}, {:}, {:?}, {?}
, ...
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 :(
The key difference between them is that printf() prints the formatted String into console much like System. out. println() but the format() method returns a formatted string, which you can store or use the way you want.
String. format returns a new String, while System. out. printf just displays the newly formatted String to System.
println is used when you want to create a new line with just simple text or even text containing concatenation. ("Hello " + "World" = "Hello World.") printf is used when you want to format your string. This will clean up any concatenation.
For thoroughness, the std::fmt
formatting syntax is composed of two parts:
{<position-or-name>:<format>}
where:
<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-timeThe 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:
?
⇒ Debugo
⇒ Octalx
⇒ LowerHexX
⇒ UpperHexp
⇒ Pointerb
⇒ Binarye
⇒ LowerExpE
⇒ UpperExpand if necessary new traits could be added in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With