Concept Flow - Formatting output
Start
Prepare data
Choose format string
Apply formatting
Print or store output
End
This flow shows how Rust takes data, applies a format string, and produces formatted output.
fn main() {
let name = "Alice";
let age = 30;
println!("Name: {}, Age: {}", name, age);
}| Step | Action | Format String | Values | Result |
|---|---|---|---|---|
| 1 | Start main function | |||
| 2 | Assign variable name | name = "Alice" | ||
| 3 | Assign variable age | age = 30 | ||
| 4 | Call println! macro | Name: {}, Age: {} | name="Alice", age=30 | Prints: Name: Alice, Age: 30 |
| 5 | End main function |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| name | uninitialized | "Alice" | "Alice" | "Alice" |
| age | uninitialized | uninitialized | 30 | 30 |
Rust formatting output uses curly braces {} as placeholders.
Use println!("text {}, {}", val1, val2) to print formatted text.
The number of placeholders must match the number of values.
Rust checks this at compile time to avoid errors.
This helps create readable and dynamic output.{} do in Rust's println! macro?{} in formatting{} acts as a placeholder where Rust inserts the value of a variable or expression inside a string.println!println!("Hello, {}", name);, Rust replaces {} with the value of name.{} = Insert value [OK]{:.2} inside println! to format a float with 2 decimal places.{:.2}, which is correct. Others use invalid or incorrect syntax.let x = 255;
println!("Decimal: {}, Hex: {:x}, Binary: {:b}", x, x, x);{} prints decimal, {:x} prints lowercase hex, {:b} prints binary.ff in hex (lowercase) and 11111111 in binary.let num = 42;
println!("Number: {2}", num);{2} means use the third argument (index 2), but only one argument num is provided.let name = "Alice"; let score = 93; // Which println! line is correct?
{:<10} aligns left in 10 spaces, {:>5} aligns right in 5 spaces.Pass the test and this pattern moves unknown