RustArena

Step 1 of 6

Storing values with let

A variable is a name for a value, so you can use the value later without typing it again. You create one with let:

fn main() {
    let player = "Ferris";
    let score = 120;
    println!("{} scored {} points", player, score);
}
Ferris scored 120 points

Piece by piece:

Calculating with variables

The right side can be any calculation, including one that uses other variables:

fn main() {
    let price = 250;
    let quantity = 3;
    let total = price * quantity;
    println!("{} x {} = {}", quantity, price, total);
}
3 x 250 = 750

Names make code explain itself: price * quantity says what is being computed, 250 * 3 doesn't.

A variable exists from its let line onward, and only inside the pair of braces { } it was declared in. That region of code is the variable's scope. Code runs from top to bottom, so a name can't be used before its let:

fn main() {
    println!("{}", score);
    let score = 120;
}
error[E0425]: cannot find value `score` in this scope
 --> src/main.rs:2:20
  |
2 |     println!("{}", score);
  |                    ^^^^^ not found in this scope

Common mistakes

Your task

Fill in the blanks: declare a variable coins holding 25, then print it, so the program prints Coins: 25.

Challenge 2

Fill in the blanks so the program adds up the length of two songs and prints Total: 7 minutes. Let Rust do the adding.

Challenge 3

Write it yourself: declare width as 7 and height as 6, then a third variable area that multiplies them, and print Area: 42. Let Rust work out the 42: don't type it yourself.

Next: Immutable by default, and mut