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.
let label = format!("{}-{:03}", "item", 7); // "item-007"
Try it
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.
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
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 withwrite!(&mut buf, ...)fromstd::fmt::Write. to_string()on aDisplayvalue does the same asformat!("{}", v); the specialization forstrand integers makes simple conversions faster than going throughformat!.- Concatenation:
a + &bworks for two strings, but beyond thatformat!("{a}{b}{c}")is clearer.[a, b].concat()andjoinare 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 anfmt::Argumentsvalue without allocating and is what logging crates use.- Alignment applies to the formatted text, but a custom
Displaythat writes directly withwrite!ignores width unless it callsf.pad(...). - Locale: formatting is locale-independent; the decimal separator is always
.. - Moves:
format!("{}", s)borrowss; passings.clone()is unnecessary.
Related
println!,write!, Format specifiers,Display,ToString,String- Lessons: Printing, Display and From