🎓 A1Learner
🔍

Rust Format Arguments

Format arguments are the values that fill {} slots in printed text. A plain slot takes its value in order.

Numbered slots pick by position

Count the arguments from 0, starting just after the text. A numbered slot can use the same argument again:

println!("{0} and {1}, then {0} again", "sun", "moon");

Numbered slots do not move the counter

A plain {} still takes the next argument in line, as if the numbered slots were not there:

println!("{1} {} {0} {}", 1, 2);

Named slots label each value

Give a value a name after the text, then use that name in a slot. The reader sees what each slot holds:

println!("{subject} {verb}", subject = "the fox", verb = "runs");

Inline slots borrow a variable

When a variable is already in scope, write its name straight in the slot — no extra argument is needed:

let score = 9;
println!("score = {score}");

Braces inside the text

The text itself may need a brace. Then double the brace. The pair collapses to a single brace. No slot is opened:

println!("{{score}} = {score}", score = 9);

Example

fn main() {
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
    println!("{subject} {verb} {object}", subject = "the quick brown fox", verb = "jumps over", object = "the lazy dog");
    println!("My name is {0}, {1} {0}", "Bond", "James");
}

Key points

  • A named argument is supplied in the call.
  • An inline {name} slot works differently.
  • It borrows a variable.
  • That variable is already in scope.
  • Scope is the part of the code where a name can be seen and used.
  • Every argument must be used.
  • One argument may be touched by no slot.
  • It may be touched by no parameter.
  • Then it is a compile error ("argument never used").
  • Rust never quietly ignores it

In this example, the first line numbers its two arguments. {0} is Alice and {1} is Bob, and the line uses each one twice, in opposite orders. The second line names its arguments instead. subject, verb and object come after the text. They come in scrambled order. Yet they print in slot order. The slots set that order. The third line mixes both ideas in miniature: {0} prints Bond, {1} prints James, and {0} prints Bond again.

Note

Rust counts slots and arguments while compiling.

A slot with no matching argument is a compile error, never a blank space at run time.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

In println!("{1} {1}", "a", "b"), what is printed?