| Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 5h ago | 1 | // `?` expands to an early return on the error branch. |
| 2 | #[derive(Debug)] |
| 3 | enum Error { |
| 4 | Odd, |
| 5 | } |
| 6 | |
| 7 | fn halve(n: i32) -> Result<i32, Error> { |
| 8 | if n % 2 != 0 { |
| 9 | return Err(Error::Odd); |
| 10 | } |
| 11 | Ok(n / 2) |
| 12 | } |
| 13 | |
| 14 | fn quarter(n: i32) -> Result<i32, Error> { |
| 15 | let half = halve(n)?; |
| 16 | let q = halve(half)?; |
| 17 | Ok(q) |
| 18 | } |
| 19 | |
| 20 | fn main() { |
| 21 | println!("{:?}", quarter(8)); |
| 22 | println!("{:?}", quarter(6)); |
| 23 | println!("{:?}", quarter(5)); |
| 24 | } |