Add lesson 8: Lifetimes demystified

Mira Kovac 9 months ago
parent 6330f69a4f commit 6826dc84112b07cc2be71c4b58f2641db5694ab8
4 changed files with 45 additions and 0 deletions
+6-0lessons/08-lifetimes-demystified/Cargo.toml ADDED
@@ -0,0 +1,6 @@
1+[package]
2+name = "lifetimes_demystified"
3+version = "0.1.0"
4+edition = "2021"
5+
6+[dependencies]
+19-0lessons/08-lifetimes-demystified/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 8: Lifetimes demystified
2+
3+This lesson covers lifetimes demystified. 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/8](https://glibcode.net/courses/rust-ownership/lessons/8)
6+
7+## Files
8+
9+- `src/main.rs`: lifetime annotations when the compiler needs them
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/08-lifetimes-demystified/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 8
2+
3+1. Make the example ask for its input instead of using a fixed value.
4+2. Add a check that prints a warning when a result looks wrong (negative, empty, too big).
5+3. Combine this lesson with the previous one: use something from both in a small program of your own.
+15-0lessons/08-lifetimes-demystified/src/main.rs ADDED
@@ -0,0 +1,15 @@
1+struct Excerpt<'a> {
2+ part: &'a str,
3+}
4+
5+fn longer<'a>(x: &'a str, y: &'a str) -> &'a str {
6+ if x.len() >= y.len() { x } else { y }
7+}
8+
9+fn main() {
10+ let novel = String::from("Call me Ishmael. Some years ago...");
11+ let first = novel.split('.').next().unwrap();
12+ let e = Excerpt { part: first };
13+ println!("{}", e.part);
14+ println!("{}", longer("short", "longer one"));
15+}