Lesson 2 · Unit 05
Enums and match
A value that is exactly one of a few things, and Option
What you practise
- Variants that carry data,
matchmust cover every case,Optioninstead of null,if let
Try a question from this lesson
Pick one
A traffic light is stored as text, and line 1 has a typo. What does the compiler do about it?
let light = String::from("gren");
if light == "green" {
println!("go");
} else {
println!("stop");
}Hint
Is "gren" a valid piece of text?
Correct answer
Nothing: the program prints stop
Why
Any text is a valid String, so the compiler cannot know that "gren" is a mistake. The program runs and quietly takes the wrong branch. A type that allows only red, yellow and green would catch it.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
An enum lists the possibilities
An enum is a type whose value is exactly one of the variants you list. You write a variant as the enum's name, ::, then the variant's name.
match picks an arm by variant, as it did with numbers. A misspelt variant is now a compile error, not a quiet bug.
enum Light { Red, Yellow, Green }
let light = Light::Green;
match light {
Light::Red => println!("stop"),
Light::Yellow => println!("slow"),
Light::Green => println!("go"),
}Concept
Variants can carry data
A variant can hold values of its own. A Shape here is either a square with one side, or a rectangle with a width and a height.
In a match, the pattern gives names to the values inside, and the arm can use them. The side of a square can only be reached in the Square arm. A rectangle has no such thing.
enum Shape {
Square(i32),
Rect(i32, i32),
}
let s = Shape::Rect(2, 5);
let area = match s {
Shape::Square(side) => side * side,
Shape::Rect(w, h) => w * h,
};
println!("{}", area);Concept
Option is an enum
Rust has no "null". A value that might be missing has the type Option, an enum from the standard library with two variants: Some(value) and None.
You met it when get looked something up. Because it is an enum, you cannot use the value inside until a match has checked that it is there.
let v = vec![10, 20, 30];
match v.get(1) {
Some(n) => println!("found {}", n),
None => println!("nothing there"),
}9 more exercises in the app
- 2× multiple choice
- 2× fill the blanks
- 3× type the answer
- 1× true or false
- 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.