Add lesson 4: Slices

Mira Kovac 10 months ago
parent 39e75dd0ae commit ed3a43afed91e0a0fc433901993b3a4084b75a49
4 changed files with 42 additions and 0 deletions
+6-0lessons/04-slices/Cargo.toml ADDED
@@ -0,0 +1,6 @@
1+[package]
2+name = "slices"
3+version = "0.1.0"
4+edition = "2021"
5+
6+[dependencies]
+19-0lessons/04-slices/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 4: Slices
2+
3+We look at slices the way working developers use it, with examples you can change and run right away.
4+
5+Full lesson: [https://glibcode.net/courses/rust-ownership/lessons/4](https://glibcode.net/courses/rust-ownership/lessons/4)
6+
7+## Files
8+
9+- `src/main.rs`: string and array slices
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/04-slices/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 4
2+
3+1. Add a comment above each block explaining what it does, in your own words.
4+2. Rewrite the main part so it runs twice with two different inputs, without copying the code.
5+3. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to?
+12-0lessons/04-slices/src/main.rs ADDED
@@ -0,0 +1,12 @@
1+fn first_word(s: &str) -> &str {
2+ s.split_whitespace().next().unwrap_or("")
3+}
4+
5+fn main() {
6+ let sentence = String::from("borrow checker friends");
7+ println!("{}", first_word(&sentence));
8+
9+ let numbers = [10, 20, 30, 40, 50];
10+ let middle = &numbers[1..4];
11+ println!("{middle:?} has {} items", middle.len());
12+}