Lesson 2 · Unit 01
Variables and types
Names for values, values that change, and the kind of each value
What you practise
let,mut, shadowing,i32,f64,boolandchar, annotations against types the compiler works out, converting withas
Try a question from this lesson
Pick one
let gives a value a name. After line 1, the name apples stands for 3. What does this print?
let apples = 3;
println!("{}", apples + 2);Correct answer
5
Why
Wherever the name appears, Rust uses the value stored under it. So apples + 2 means 3 + 2. The name is not in quotes, so it is not text.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Variables
A variable is a name for a value. let price = 4; stores 4 under the name price.
Later lines can use the name in a calculation, or put it straight into a gap: {price}.
Pick names that say what the value is. price beats p.
let price = 4;
let count = 3;
println!("{}", price * count);
println!("total: {price} x {count}");Concept
Values that change: `mut`
Write let mut to make a variable that may change. mut is short for mutable: able to change.
score = 15; replaces the value. score += 1; adds 1 to it, and -=, *= and /= work the same way.
Why is change off unless you ask? When you read a plain let, you know that value stays the same to the end.
let mut score = 10;
score = 15;
score += 1;
println!("{score}");Concept
Every value has a type
A type is the kind of a value. Four to start with: i32 is a whole number, f64 is a decimal, bool is true or false, and char is one character in single quotes.
Rust works the type out from the value. You can also write it yourself after a colon.
Text after // is a note for people. Rust ignores it.
let age = 30; // i32
let price: f64 = 2.5;
let open: bool = true;
let grade: char = 'A';
println!("{age} {price} {open} {grade}");9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 2× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.