Rust Tutorial · Rust Basics · Lesson 3 of 29
Rust Syntax and Printing
Statements, expressions, comments, and formatted output with println! and format!.
Expressions everywhere
Almost everything in Rust is an expression that produces a value; a block's last expression (without a semicolon) is its value.
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 aStringthe same way.
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!?
None{} uses Display, {:?} uses Debug formatting{:?} prints the type{} only works for strings
Show answer
Answer: {} uses Display, {:?} uses Debug formatting