Add lesson 7: Error handling with Result
4 changed files with 44 additions and 0 deletions
lessons/07-error-handling-with-result/Cargo.toml ADDED
| @@ -0,0 +1,6 @@ | ||
| 1 | +[package] | |
| 2 | +name = "error_handling_with_resu" | |
| 3 | +version = "0.1.0" | |
| 4 | +edition = "2021" | |
| 5 | + | |
| 6 | +[dependencies] | |
lessons/07-error-handling-with-result/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 7: Error handling with Result | |
| 2 | + | |
| 3 | +We look at error handling with Result 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/7](https://glibcode.net/courses/rust-ownership/lessons/7) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `src/main.rs`: Result, the ? operator and a custom error | |
| 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/07-error-handling-with-result/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 7 | |
| 2 | + | |
| 3 | +1. Combine this lesson with the previous one: use something from both in a small program of your own. | |
| 4 | +2. Explain the example to someone who hasn't taken the course. Which part was hardest to explain? | |
| 5 | +3. Add a comment above each block explaining what it does, in your own words. | |
lessons/07-error-handling-with-result/src/main.rs ADDED
| @@ -0,0 +1,14 @@ | ||
| 1 | +use std::fs; | |
| 2 | + | |
| 3 | +fn read_port(path: &str) -> Result<u16, Box<dyn std::error::Error>> { | |
| 4 | + let text = fs::read_to_string(path)?; | |
| 5 | + let port: u16 = text.trim().parse()?; | |
| 6 | + Ok(port) | |
| 7 | +} | |
| 8 | + | |
| 9 | +fn main() { | |
| 10 | + match read_port("port.txt") { | |
| 11 | + Ok(port) => println!("listening on {port}"), | |
| 12 | + Err(e) => eprintln!("could not read the port: {e}"), | |
| 13 | + } | |
| 14 | +} | |