Add lesson 5: Structs and enums

Mira Kovac 9 months ago
parent ed3a43afed commit d2601327450462c6195cfcd722e531fc303b05ac
4 changed files with 57 additions and 0 deletions
+6-0lessons/05-structs-and-enums/Cargo.toml ADDED
@@ -0,0 +1,6 @@
1+[package]
2+name = "structs_and_enums"
3+version = "0.1.0"
4+edition = "2021"
5+
6+[dependencies]
+19-0lessons/05-structs-and-enums/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 5: Structs and enums
2+
3+This lesson covers structs and enums. 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/5](https://glibcode.net/courses/rust-ownership/lessons/5)
6+
7+## Files
8+
9+- `src/main.rs`: structs with methods and an enum
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/05-structs-and-enums/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 5
2+
3+1. Rewrite the main part so it runs twice with two different inputs, without copying the code.
4+2. Find one thing in `src/main.rs` you could name better and rename it everywhere.
5+3. Explain the example to someone who hasn't taken the course. Which part was hardest to explain?
+27-0lessons/05-structs-and-enums/src/main.rs ADDED
@@ -0,0 +1,27 @@
1+#[derive(Debug)]
2+enum Status {
3+ Todo,
4+ Done,
5+}
6+
7+#[derive(Debug)]
8+struct Task {
9+ title: String,
10+ status: Status,
11+}
12+
13+impl Task {
14+ fn new(title: &str) -> Self {
15+ Task { title: title.to_string(), status: Status::Todo }
16+ }
17+
18+ fn finish(&mut self) {
19+ self.status = Status::Done;
20+ }
21+}
22+
23+fn main() {
24+ let mut t = Task::new("write lesson 5");
25+ t.finish();
26+ println!("{t:?}");
27+}