Add lesson 3: Borrowing and references

Mira Kovac 10 months ago
parent c4a8cd687d commit 39e75dd0ae5b918a1a40de57ce06ec355944b30f
4 changed files with 50 additions and 0 deletions
+6-0lessons/03-borrowing-and-references/Cargo.toml ADDED
@@ -0,0 +1,6 @@
1+[package]
2+name = "borrowing_and_references"
3+version = "0.1.0"
4+edition = "2021"
5+
6+[dependencies]
+19-0lessons/03-borrowing-and-references/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 3: Borrowing and references
2+
3+This lesson covers borrowing and references. 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/3](https://glibcode.net/courses/rust-ownership/lessons/3)
6+
7+## Files
8+
9+- `src/main.rs`: shared and mutable references
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/03-borrowing-and-references/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 3
2+
3+1. Combine this lesson with the previous one: use something from both in a small program of your own.
4+2. Time yourself: rewrite the example from memory in 10 minutes, then diff it against the original.
5+3. Rewrite the main part so it runs twice with two different inputs, without copying the code.
+20-0lessons/03-borrowing-and-references/src/main.rs ADDED
@@ -0,0 +1,20 @@
1+fn longest(words: &[String]) -> &str {
2+ let mut best = "";
3+ for w in words {
4+ if w.len() > best.len() {
5+ best = w;
6+ }
7+ }
8+ best
9+}
10+
11+fn add_exclamation(s: &mut String) {
12+ s.push('!');
13+}
14+
15+fn main() {
16+ let mut words = vec![String::from("cat"), String::from("giraffe")];
17+ println!("{}", longest(&words));
18+ add_exclamation(&mut words[0]);
19+ println!("{words:?}");
20+}