Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between println's format styles?

Tags:

rust

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 :(

like image 728
kai Avatar asked Oct 18 '16 05:10

kai


People also ask

What is the difference between Println and format in Java?

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.

What is the difference between String format and System out printf?

String. format returns a new String, while System. out. printf just displays the newly formatted String to System.

What is the difference between System out printf and System out println in Java?

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.


1 Answers

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-time

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:

  • nothing ⇒ Display
  • ? ⇒ Debug
  • o ⇒ Octal
  • x ⇒ LowerHex
  • X ⇒ UpperHex
  • p ⇒ Pointer
  • b ⇒ Binary
  • e ⇒ LowerExp
  • E ⇒ UpperExp

and if necessary new traits could be added in the future.

like image 154
Matthieu M. Avatar answered Nov 09 '22 02:11

Matthieu M.