String formatting

1 min read

Starting Rust 1.58

Format strings can now capture arguments simply by writing {ident} in the string.

Examples:

let x = "world";
println!("Hello {x}!"); // Hello world

let items = vec![10, 20, 30];
println!("{items:?}")  // Debug printing
println!("{items:#?}") // Pretty printing

Optionally, flags can be specified like {identifier:flags}

Alignment

  • print item min-width of 10 - println!("{item:10})
  • same, but center align - println!("{item:^10})
  • same, but right align - println!("{item:>10})

Formatting numbers

  • Always print the sign of the number - println!("{y:+}");
  • Hex, binary and octal - println!("{y:#x} {y:#b} {y:#o}");
  • Float precision. 5 digits after decimal points - println!("{z:.5}")

Sources