Add lesson 6: Pattern matching

Mira Kovac 9 months ago
parent d260132745 commit 44184310f1d7088a903699f1426b0ffa2fb67cdc
4 changed files with 55 additions and 0 deletions
+6-0lessons/06-pattern-matching/Cargo.toml ADDED
@@ -0,0 +1,6 @@
1+[package]
2+name = "pattern_matching"
3+version = "0.1.0"
4+edition = "2021"
5+
6+[dependencies]
+19-0lessons/06-pattern-matching/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 6: Pattern matching
2+
3+This lesson covers pattern matching. You'll read a short explanation, try three small exercises and finish with a quiz.
4+
5+Full lesson: [https://glibcode.net/courses/rust-ownership/lessons/6](https://glibcode.net/courses/rust-ownership/lessons/6)
6+
7+## Files
8+
9+- `src/main.rs`: match on enums, tuples and ranges
10+
11+## Run it
12+
13+```sh
14+cargo run
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/06-pattern-matching/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 6
2+
3+1. Combine this lesson with the previous one: use something from both in a small program of your own.
4+2. Add a check that prints a warning when a result looks wrong (negative, empty, too big).
5+3. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to?
+25-0lessons/06-pattern-matching/src/main.rs ADDED
@@ -0,0 +1,25 @@
1+enum Shape {
2+ Circle(f64),
3+ Rect { w: f64, h: f64 },
4+}
5+
6+fn area(s: &Shape) -> f64 {
7+ match s {
8+ Shape::Circle(r) => std::f64::consts::PI * r * r,
9+ Shape::Rect { w, h } => w * h,
10+ }
11+}
12+
13+fn size(n: u32) -> &'static str {
14+ match n {
15+ 0 => "none",
16+ 1..=9 => "a few",
17+ _ => "lots",
18+ }
19+}
20+
21+fn main() {
22+ println!("{:.2}", area(&Shape::Circle(1.5)));
23+ println!("{}", area(&Shape::Rect { w: 2.0, h: 3.0 }));
24+ println!("{}", size(12));
25+}