Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust format! macro

Reference for the Rust format! macro: build a String from a format string, compare with to_string and concatenation, format_args!, and performance tips.

format! works exactly like println!, but instead of printing it returns the result as a new String. It is the usual way to build text out of several values: numbers padded to a width, structs through their Display or Debug implementation, or pieces of other strings.

The macro never moves or borrows its arguments in a way that lasts: it takes references to them, so the values are still usable after the call.

Rust
let label = format!("{}-{:03}", "item", 7); // "item-007"

Try it

Rust Building strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust format! with custom types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
format!("format string", args...) -> String
Name Description
format string A string literal with {} placeholders; see Format specifiers.
args Positional, named (name = value) or inline-captured values.

Returns: a newly allocated String.

Errors / panics / edge cases: a panic occurs if a Display or Debug implementation returns an error (for example a custom fmt that fails), with the message "a formatting trait implementation returned an error". Wrong argument counts or missing trait implementations are compile errors.

Usage notes

  • Allocation: every call allocates a String (the macro estimates a capacity from the pieces). For one-off values that is fine; in hot loops, reuse a buffer with write!(&mut buf, ...) from std::fmt::Write.
  • to_string() on a Display value does the same as format!("{}", v); the specialization for str and integers makes simple conversions faster than going through format!.
  • Concatenation: a + &b works for two strings, but beyond that format!("{a}{b}{c}") is clearer. [a, b].concat() and join are better for lists.
  • Inline captures work only for plain identifiers, not for expressions such as {self.name}. Pass those as arguments.
  • format_args! is the lower-level macro behind all of them. It builds an fmt::Arguments value without allocating and is what logging crates use.
  • Alignment applies to the formatted text, but a custom Display that writes directly with write! ignores width unless it calls f.pad(...).
  • Locale: formatting is locale-independent; the decimal separator is always ..
  • Moves: format!("{}", s) borrows s; passing s.clone() is unnecessary.