How to Format Strings in Rust with format!

Use the `format!` macro to construct new `String` values by embedding expressions directly into a template string, similar to C's `printf` but with type safety and no format string vulnerabilities.

Use the format! macro to construct new String values by embedding expressions directly into a template string, similar to C's printf but with type safety and no format string vulnerabilities. It supports positional arguments, named arguments, and various formatting specifiers for alignment, padding, and base conversion.

Here is a practical example using positional arguments and common specifiers:

fn main() {
    let name = "Alice";
    let age = 30;
    let score = 98.5;

    // Basic interpolation, integer alignment, and float precision
    let greeting = format!("Hello, {}! You are {} years old.", name, age);
    let report = format!("Score: {:>5.2} (aligned right, 2 decimals)", score);

    println!("{}", greeting); // Output: Hello, Alice! You are 30 years old.
    println!("{}", report);   // Output: Score:  98.50 (aligned right, 2 decimals)
}

You can also use named arguments for better readability in complex templates, or specify bases for integers (hex, binary, octal):

fn main() {
    let width = 10;
    let height = 20;
    let id = 255;

    // Named arguments and base conversion
    let dimensions = format!("Size: {width}x{height}", width = width, height = height);
    let hex_id = format!("ID: {:#x}", id); // # adds '0x' prefix

    println!("{}", dimensions); // Output: Size: 10x20
    println!("{}", hex_id);     // Output: ID: 0xff
}

Key formatting specifiers include {:?} for debug output, {:?} for pretty printing, and {} for default display. Alignment is controlled by < (left), > (right), or ^ (center), followed by a width number (e.g., {:>10}). Precision for floats is set with . followed by the digit count (e.g., {:.2}). Remember that format! allocates a new String on the heap; if you only need to print to stdout without storing the result, use println! or print! instead to avoid unnecessary allocation.