Dynamic Error Types

Sometimes we want to allow any type of error to be returned without writing our own enum covering all the different possibilities. The std::error::Error trait makes it easy to create a trait object that can contain any error.

1. ```
   use std::error::Error;
   ```
2. ```
   use std::fs;
   ```
3. ```
   use std::io::Read;
   ```

5. ```
   fn read_count(path: &str) -> Result<i32, Box<dyn Error>> {
   ```
6. ```
       let mut count_str = String::new();
   ```
7. ```
       fs::File::open(path)?.read_to_string(&mut count_str)?;
   ```
8. ```
       let count: i32 = count_str.parse()?;
   ```
9. ```
       Ok(count)
   ```
10. ```
    }
    ```

12. ```
    fn main() {
    ```
13. ```
        fs::write("count.dat", "1i3").unwrap();
    ```
14. ```
        match read_count("count.dat") {
    ```
15. ```
            Ok(count) => println!("Count: {count}"),
    ```
16. ```
            Err(err) => println!("Error: {err}"),
    ```
17. ```
        }
    ```
18. ```
    }
    ```

This slide should take about 5 minutes.

The read_count function can return std::io::Error (from file operations) or std::num::ParseIntError (from String::parse).

Boxing errors saves on code, but gives up the ability to cleanly handle different error cases differently in the program. As such it’s generally not a good idea to use Box<dyn Error> in the public API of a library, but it can be a good option in a program where you just want to display the error message somewhere.

Make sure to implement the std::error::Error trait when defining a custom error type so it can be boxed.