Lesson 1 · Unit 02
Structs and enums
Fields, methods and variants that hold data
What you practise
- Fields and
implblocks, enums whose variants hold data, a shape or a message modelled both ways
Try a question from this lesson
Pick one
The rules for &mut apply to methods too. Which line does the compiler reject?
struct Counter { n: u32 }
impl Counter {
fn bump(&mut self) {
self.n += 1;
}
}
let c = Counter { n: 0 };
c.bump();Hint
c.bump() is short for borrowing c mutably. Is c allowed to change?
Correct answer
Line 8
Why
Calling a &mut self method takes &mut c behind the scenes, and c was not declared mut. The method itself is fine. The fix is let mut c on line 7.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Methods live in impl
A struct holds only data. Its methods go in a separate impl block.
A method's first parameter is self in some form. &self borrows the value to read it, the same & as any other borrow. Python's self is always a shared reference. In Rust you pick how much access the method gets.
struct Rect { w: u32, h: u32 }
impl Rect {
fn area(&self) -> u32 {
self.w * self.h
}
}
let r = Rect { w: 3, h: 4 };
println!("{}", r.area());Concept
Enums whose variants hold data
An enum is a type that is one of several variants. Unlike Python's Enum, each variant can carry its own data: nothing, a tuple of values or named fields.
A Shape is a circle or a rectangle, never both and never neither. Wrong combinations cannot be written down, so they need no checks.
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
}
let a = Shape::Circle(1.5);
let b = Shape::Rect { w: 2.0, h: 3.0 };10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 2× multiple choice
- 1× match the pairs
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.