What is the difference between println format styles?

I am very sorry to ask such a simple question ... A day ago, I began to study Rust and tried the println! method println! .

 fn main() { println!("Hello {}!", "world"); } -> Hello world! 

And then I found other format styles: {}, {:}, {:?}, {?} , ...

I know that {} String instead, but I don't understand a different formatting style. How do these styles differ from each other? I think {:?} Is an array or a vector. Is it correct?

Please explain this formatting style with a sample code :(

+5
source share
2 answers

For thoroughness, the formatting syntax for std::fmt consists of two parts:

 {<position-or-name>:<format>} 

Where:

  • <position-or-name> may be the position of the argument: println!("Hello {0}!" , "world"); `, note that it is checked at compile time
  • <position-or-name> could also be a name: println!("Hello {arg}!", arg = "world");
  • <format> is one of the following formats , where each format requires an argument to implement a particular attribute, noted at compile time

By default, if there is no position, name or format, select the argument corresponding to the index {} and use the Display flag. However, there are different features! By the link above:

  • nothing โ‡’ Display
  • ? โ‡’ Debugging
  • o โ‡’ Octal
  • x โ‡’ LowerHex
  • x โ‡’ UpperHex
  • p โ‡’ Index
  • b โ‡’ Binary
  • e โ‡’ LowerExp
  • e โ‡’ UpperExp

and if necessary, new features may be added in the future.

+12
source

println!() is a macro that uses the std::fmt syntax and {} specifies parameters. If the brackets are left empty ( {} ), the corresponding argument must implement the Display flag, and if they contain :? , this means that you should use the Debug implementation instead.

The bottom line is that the type of parameters does not apply here, but the properties that they implement . For example, Vec tors implement Debug , but they do not implement Display , and therefore you cannot use {} against them, and {:?} Works just fine.

+4
source

Source: https://habr.com/ru/post/1258378/


All Articles