RustArena

Step 4 of 6

Printing values with {}

println! can do more than print fixed text. Inside the string, a pair of curly braces {} is a placeholder: a hole that gets filled with a value you put after the string, separated by commas. The string with the holes is called the format string.

fn main() {
    println!("2 + 3 = {}", 2 + 3);
    println!("{} likes {}", "Ferris", "Rust");
}
2 + 3 = 5
Ferris likes Rust

The values fill the placeholders in order: the first {} gets the first value, and so on. Rust checks this when it compiles: if the number of {} and values don't match, it's a compile error, not a surprise at run time.

Arithmetic

Rust does the math before printing: + adds, - subtracts, * multiplies, / divides and % gives the remainder. With whole numbers, / drops the fraction: 7 / 2 is 3. You'll see why in the Types module.

Printing braces

To print an actual { or }, double it: {{ and }}.

fn main() {
    println!("{{}} is a placeholder, and 10 / 3 = {}", 10 / 3);
}
{} is a placeholder, and 10 / 3 = 3

Your task

Fill the blanks so the program prints 6 * 7 = 42, with Rust working out the 42 (don't type the answer yourself).

Challenge 2

Print The crab has 10 legs where the 10 comes from a value after the format string (put 10 as an argument, not inside the text).

Challenge 3

Write a println! with three placeholders that prints 1 + 2 = 3. The three values after the format string should be 1, 2 and 1 + 2.

Previous: Several lines, and print! versus println! Next: Comments and reading compiler errors