| Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 5h ago | 1 | // Result-returning functions, Ok/Err construction, and matching on both. |
| 2 | #[derive(Debug, PartialEq)] |
| 3 | enum Error { |
| 4 | TooBig, |
| 5 | } |
| 6 | |
| 7 | fn halve(n: i32) -> Result<i32, Error> { |
| 8 | if n > 100 { |
| 9 | Err(Error::TooBig) |
| 10 | } else { |
| 11 | Ok(n / 2) |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | fn main() { |
| 16 | for n in [10, 200] { |
| 17 | match halve(n) { |
| 18 | Ok(v) => println!("ok {}", v), |
| 19 | Err(e) => println!("err {:?}", e), |
| 20 | } |
| 21 | } |
| 22 | println!("{:?}", halve(8)); |
| 23 | println!("{}", halve(8).unwrap()); |
| 24 | println!("{} {}", halve(8).is_ok(), halve(500).is_err()); |
| 25 | } |