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:
letstarts a variable declaration. Rust calls this binding a name to a value: after this line, the namescoreis bound to120.- The
=means "is bound to", not "equals" in the math sense. The right side is worked out first, then the result gets the name on the left. - The
;ends the statement, just like afterprintln!. - From then on, writing
score(without quotes) means "the value bound toscore". Here it fills a{}placeholder.
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
- Forgetting
let:score = 120;on its own means "change the existing variablescore". If there isn't one, you get the same E0425 error as above. - Quotes around the name:
println!("{}", "score")prints the wordscore. A bare name is a variable; text in double quotes is a string literal. - Spaces or dashes in names:
let total priceandlet total-pricedon't work. Names are one word; join words with_:total_price.
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.