println! and formatting
- Rust course
- Beginner
- Lesson 4/115
- 4 min
Print variables with the println! macro and the {} placeholder.
println! and formatting
The {} placeholder writes the value in a user-friendly way; {:?} writes it in debug format. A variable name can be written directly inside the braces:
let ad = "Ada";
let yas = 36;
println!("{} {} yaşında", ad, yas);
println!("{ad} {yas} yaşında"); // same result
println!("{:?}", vec![1, 2, 3]); // [1, 2, 3]The format string is checked at compile time; if the number of placeholders and arguments differ, the code doesn't compile.
Width and precision
Format options are added to the placeholder:
let pi = 3.14159;
println!("{:.2}", pi); // 3.14
println!("[{:>6}]", 42); // [ 42]
println!("[{:<6}]", 42); // [42 ]
println!("[{:06}]", 42); // [000042]
println!("{:#?}", (1, "a")); // multi-line Debugformat! uses the same syntax but returns a String instead of printing.
Practice Formatted price
Declare let urun = "Kalem"; and let fiyat = 12.5;. Print with inline variable names: println!("{urun}: {fiyat:.2} TL");.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let urun = "Kalem";
let fiyat = 12.5;
println!("{urun}: {fiyat:.2} TL");
}Expected output
Kalem: 12.50 TL
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which placeholder is needed to print a vector?
- %v
- {v}
- {:?} Correct answer
- {}
Explanation: Vec doesn't implement Display but implements Debug; so {:?} is needed. Using {} is a compile error.
2 Two decimals
println!("{____}", 2.71828); // 2.72
println!("{:.2}", 2.71828); // 2.72
Explanation: :.2 writes the number with two decimal places.
3 Format and output
| Term | Meaning |
|---|---|
{} |
Display format |
{:?} |
Debug format |
{:.2} |
Two decimals |
{:>6} |
Right-aligned, width 6 |