Add lesson 9: Traits and generics
4 changed files with 53 additions and 0 deletions
lessons/09-traits-and-generics/Cargo.toml ADDED
| @@ -0,0 +1,6 @@ | ||
| 1 | +[package] | |
| 2 | +name = "traits_and_generics" | |
| 3 | +version = "0.1.0" | |
| 4 | +edition = "2021" | |
| 5 | + | |
| 6 | +[dependencies] | |
lessons/09-traits-and-generics/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 9: Traits and generics | |
| 2 | + | |
| 3 | +Traits and generics comes up in almost every real Rust project. We start with the why, then write code together. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/rust-ownership/lessons/9](https://glibcode.net/courses/rust-ownership/lessons/9) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `src/main.rs`: a trait, an impl and a generic function | |
| 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. | |
lessons/09-traits-and-generics/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 9 | |
| 2 | + | |
| 3 | +1. Run `src/main.rs` and change one value. Write down what you expect, then run it again and compare. | |
| 4 | +2. Find one thing in `src/main.rs` you could name better and rename it everywhere. | |
| 5 | +3. Add a check that prints a warning when a result looks wrong (negative, empty, too big). | |
lessons/09-traits-and-generics/src/main.rs ADDED
| @@ -0,0 +1,23 @@ | ||
| 1 | +trait Describe { | |
| 2 | + fn describe(&self) -> String; | |
| 3 | +} | |
| 4 | + | |
| 5 | +struct Dog; | |
| 6 | +struct Robot { model: u32 } | |
| 7 | + | |
| 8 | +impl Describe for Dog { | |
| 9 | + fn describe(&self) -> String { "a good dog".into() } | |
| 10 | +} | |
| 11 | + | |
| 12 | +impl Describe for Robot { | |
| 13 | + fn describe(&self) -> String { format!("robot model {}", self.model) } | |
| 14 | +} | |
| 15 | + | |
| 16 | +fn introduce<T: Describe>(thing: &T) { | |
| 17 | + println!("This is {}", thing.describe()); | |
| 18 | +} | |
| 19 | + | |
| 20 | +fn main() { | |
| 21 | + introduce(&Dog); | |
| 22 | + introduce(&Robot { model: 42 }); | |
| 23 | +} | |