Rust

Format Strings (println! / write!)

admin by @admin ADMIN
Jun 19, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Rust's format macros take an inline format string with `{}` placeholders. Named arguments, alignment, precision, debug formatting — all in the format spec.
Rust
Raw
fn main() {
    let n   = 42;
    let pi  = std::f64::consts::PI;
    let txt = "rust";

    // Inline variable capture (Rust 1.58+) — most readable
    println!("{n}");                              // 42
    println!("{txt} is {n}");                     // rust is 42

    // Width, fill, alignment: {:<10} left, {:>10} right, {:^10} center
    println!("{txt:>10}");                        // "      rust"
    println!("{n:05}");                           // "00042"  — pad with zeros

    // Precision for floats
    println!("{pi:.2}");                          // 3.14
    println!("{pi:>10.4}");                       // "    3.1416"

    // Debug vs Display
    let v = vec![1, 2, 3];
    println!("{v:?}");                            // [1, 2, 3]   — Debug
    println!("{v:#?}");                           // pretty-printed Debug

    // Hex / binary / octal
    println!("{n:x} {n:b} {n:o}");                // 2a 101010 52
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.