CodeBlanks Logo Icon CodeBlanks

println! and formatting

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 Debug

format! 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

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
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

Question
println!("{____}", 2.71828);  // 2.72
Answer
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

All lessons in Beginner