Rust Tutorial · Rust Basics · Lesson 3 of 29

Rust Syntax and Printing

Statements, expressions, comments, and formatted output with println! and format!.

Create a free account to save this page, take notes and track your progress. Sign in

Expressions everywhere

Almost everything in Rust is an expression that produces a value; a block's last expression (without a semicolon) is its value.

Blocks and if are expressions
fn main() {
    // A block is an expression: its last line (no semicolon) is the value
    let total = {
        let price = 25;
        let quantity = 3;
        price * quantity
    };
    let label = if total > 50 { "large order" } else { "small order" };
    println!("{total} -> {label}");
}

Output

75 -> large order

Run this on your computer — see “Get Started” for setup.

Formatting

  • {} uses the Display format; {:?} the Debug format ({:#?} pretty-printed).
  • Variables can be named inline: {name}; width and precision: {:>8}, {:.2}.
  • format! builds a String the same way.
Formatting output
fn main() {
    let name = "Ana";
    let balance = 1234.5678;
    let items = vec!["mug", "teapot"];
    println!("{name} has {balance:.2} EUR");
    println!("[{:>8}] [{:<8}] [{:^8}]", "right", "left", "mid");
    println!("{items:?}");
    let report = format!("{} items for {}", items.len(), name);
    println!("{report}");
}

Output

Ana has 1234.57 EUR
[   right] [left    ] [  mid   ]
["mug", "teapot"]
2 items for Ana

Run this on your computer — see “Get Started” for setup.

Test yourself

What's the difference between {} and {:?} in println!?

  1. None
  2. {} uses Display, {:?} uses Debug formatting
  3. {:?} prints the type
  4. {} only works for strings
Show answer

Answer: {} uses Display, {:?} uses Debug formatting

Was this page helpful?