Add lesson 2: Ownership: who frees the memory
4 changed files with 44 additions and 0 deletions
lessons/02-ownership-who-frees-the-memory/Cargo.toml ADDED
| @@ -0,0 +1,6 @@ | ||
| 1 | +[package] | |
| 2 | +name = "ownership_who_frees_the_" | |
| 3 | +version = "0.1.0" | |
| 4 | +edition = "2021" | |
| 5 | + | |
| 6 | +[dependencies] | |
lessons/02-ownership-who-frees-the-memory/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 2: Ownership: who frees the memory | |
| 2 | + | |
| 3 | +Ownership: who frees the memory 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/2](https://glibcode.net/courses/rust-ownership/lessons/2) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `src/main.rs`: moves: why the first String is gone | |
| 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/02-ownership-who-frees-the-memory/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 2 | |
| 2 | + | |
| 3 | +1. Rewrite the main part so it runs twice with two different inputs, without copying the code. | |
| 4 | +2. Run `src/main.rs` and change one value. Write down what you expect, then run it again and compare. | |
| 5 | +3. Look up one function or command the example uses in the official documentation. Note one option you didn't know. | |
lessons/02-ownership-who-frees-the-memory/src/main.rs ADDED
| @@ -0,0 +1,14 @@ | ||
| 1 | +fn shout(text: String) -> String { | |
| 2 | + text.to_uppercase() | |
| 3 | +} | |
| 4 | + | |
| 5 | +fn main() { | |
| 6 | + let greeting = String::from("hello"); | |
| 7 | + let loud = shout(greeting); // greeting moves into shout | |
| 8 | + // println!("{greeting}"); // error[E0382]: borrow of moved value | |
| 9 | + println!("{loud}"); | |
| 10 | + | |
| 11 | + let a = String::from("copy me"); | |
| 12 | + let b = a.clone(); // an explicit, visible copy | |
| 13 | + println!("{a} / {b}"); | |
| 14 | +} | |