liveBook · Manning

Format! macro

As explained in Learn Rust in a Month of Lunches

The format! macro constructs a formatted String instead of writing formatted output.

The format! macro constructs a String from formatted text instead of printing the result. It works like println!, but saves the finished text for later use. section 2.2

Combining names into a String

fn main() { let name = "Billybrobby"; let country = "USA"; let home = "Korea"; let together = format!("I am {name} from {country} but I live in {home}."); } section 2.2

The resulting value is stored in together, but nothing is printed until you pass that String to an output operation. This makes format! useful when formatted text must become data. section 2.2

A closure can also use format! to create a detailed error message, such as identifying which company has no CEO, before returning it as a String error. section 9.1.1

fn main() {
    let name = "Billybrobby";
    let country = "USA";
    let home = "Korea";
    let together = format!("I am {name} from {country} but I live in {home}.");
}

See the minimal example that interpolates three variables into one stored String. section 2.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains the println! relationship and demonstrates interpolation, but does not detail macro expansion or formatting internals.
Examples
Uses interpolated names and locations, then creates company-specific missing-CEO error messages.
What you can do after
Apply it via Rust's format! macro to assemble reusable formatted Strings and custom error messages.
How it connects
Connects format! with println!, String, closures, Result, and error messages.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.