RRust By Example

String Formatting

Format strings with format! macro and various specifiers.

String Formatting

Format strings with format! macro and various specifiers.

Difficulty

Beginner

Code

rust
fn main() {
    // basic interpolation
    let name = "Rust";
    let version = 2024;
    let s = format!("{} {}", name, version);
    println!("{}", s);

    // positional arguments
    let s = format!("{0} is {1}, {1} is {0}", "first", "second");
    println!("{}", s);

    // named arguments
    let s = format!("{lang} is {adj}", lang = "Rust", adj = "awesome");
    println!("{}", s);

    // formatting numbers
    println!("binary: {:b}", 42);
    println!("octal: {:o}", 42);
    println!("hex: {:x}", 42);
    println!("padded: {:08}", 42);
    println!("float: {:.3}", 3.14159);
}

Explanation

format! creates formatted strings with specifiers.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the compound-types category to build a complete understanding of this topic.

More Compound Types Examples