0
0
Rustprogramming~10 mins

Formatting output in Rust - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Rust
fn main() {
    let name = "Alice";
    let age = 30;
    println!("Name: {}, Age: {}", name, age);
}
This code prints a formatted string with a name and age using placeholders.
Execution Table
StepActionFormat StringValuesResult
1Start main function
2Assign variable namename = "Alice"
3Assign variable ageage = 30
4Call println! macroName: {}, Age: {}name="Alice", age=30Prints: Name: Alice, Age: 30
5End main function
💡 Program ends after printing formatted output.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
nameuninitialized"Alice""Alice""Alice"
ageuninitializeduninitialized3030
Key Moments - 2 Insights
Why do we use curly braces {} in the format string?
Curly braces {} are placeholders that tell Rust where to insert the values, as shown in step 4 of the execution_table.
What happens if the number of placeholders doesn't match the number of values?
Rust will give a compile-time error because the println! macro expects the number of placeholders to match the number of values, as implied in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is printed?
AName: Alice, Age: 30
BName: {}, Age: {}
CAlice 30
DName: name, Age: age
💡 Hint
Check the Result column in step 4 of the execution_table.
According to variable_tracker, what is the value of 'age' after step 3?
Auninitialized
B30
C"Alice"
D0
💡 Hint
Look at the 'age' row under 'After Step 3' in variable_tracker.
If we add another placeholder {} in the format string but do not add a value, what will happen?
AThe program prints an extra empty space
BThe program ignores the extra placeholder
CRust gives a compile-time error
DThe program crashes at runtime
💡 Hint
Refer to key_moments about placeholder and value count matching.
Concept Snapshot
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.
Full Transcript
This example shows how Rust formats output using the println! macro. First, variables name and age are assigned values. Then, the println! macro is called with a format string containing curly braces {} as placeholders. The values of name and age are inserted into these placeholders in order. The program prints the final string: "Name: Alice, Age: 30". If the number of placeholders and values do not match, Rust will give a compile-time error. This ensures safe and clear formatting of output.