D. Ataro
D. Ataro

Reputation: 1821

What does the type in the formatting types syntax do?

What does the ‘type’ in the formatting types syntax of format! do?

Of this, that is:

[[fill]align][sign]['#']['0'][width]['.' precision][type]

The rest appears to be well documented, but that particular one seems to have some information left out. Under its explanation it says:

type := identifier | ''

But what on Earth is it used for?

Edits

1.

Someone suggested that they be for named parameters, and that feels reasonable to assume. However, should the following code not work had that been the case?

println!("{:.2test}", test=32.432);

This generates me a rather depressing error:

error: unknown format trait `test`
  --> src\main.rs:12:29
   |
12 |    println!("{:.2test}", test=32.432);
   |                               ^^^^^^

Upvotes: 1

Views: 110

Answers (1)

E_net4
E_net4

Reputation: 30032

What must be noted here is that the syntax above is for format_spec, which always follows a colon.

format := '{' [ argument ] [ ':' format_spec ] '}'

format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type]

With that in mind, the type part is used to specify formatting traits, which are documented as thus:

When requesting that an argument be formatted with a particular type, you are actually requesting that an argument ascribes to a particular trait. This allows multiple actual types to be formatted via {:x} (like i8 as well as isize).

[...]

If no format is specified (as in {} or {:6}), then the format trait used is the Display trait.

Here's an example (Playground):

println!("{:b}", 31); // prints 11111
println!("{:08b}", 31); // prints 00011111

Type formatting works for any data type that implements the corresponding formatting type, such as Binary or LowerHex.


At first I guessed it would be named parameters, but those actually go before the colon. Just for the record, this also works (Playground):

format!("{a:08b}", a = 31)

Upvotes: 3

Related Questions