diff options
| author | Hunter Kvalevog <hunter@kvog.sh> | 2026-09-27 12:11:32 -0500 |
|---|---|---|
| committer | Hunter Kvalevog <hunter@kvog.sh> | 2026-09-27 12:11:32 -0500 |
| commit | b9b008c1d4a730335bdc9d465b0fdf7869fb09d4 (patch) | |
| tree | e9695905445b4bab89c07b8662fe40207b74c288 /rustlings/solutions/13_error_handling/errors5.rs | |
| parent | 1da0f56d76e5d5117eac05af092bf0ab58b14c8f (diff) | |
rustlings: complete 13
Diffstat (limited to 'rustlings/solutions/13_error_handling/errors5.rs')
| -rw-r--r-- | rustlings/solutions/13_error_handling/errors5.rs | 56 |
1 files changed, 53 insertions, 3 deletions
diff --git a/rustlings/solutions/13_error_handling/errors5.rs b/rustlings/solutions/13_error_handling/errors5.rs index dcf2377..c1424ee 100644 --- a/rustlings/solutions/13_error_handling/errors5.rs +++ b/rustlings/solutions/13_error_handling/errors5.rs @@ -1,4 +1,54 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. +// This exercise is an altered version of the `errors4` exercise. It uses some +// concepts that we won't get to until later in the course, like `Box` and the +// `From` trait. It's not important to understand them in detail right now, but +// you can read ahead if you like. For now, think of the `Box<dyn ???>` type as +// an "I want anything that does ???" type. +// +// In short, this particular use case for boxes is for when you want to own a +// value and you care only that it is a type which implements a particular +// trait. To do so, The `Box` is declared as of type `Box<dyn Trait>` where +// `Trait` is the trait the compiler looks for on any value used in that +// context. For this exercise, that context is the potential errors which +// can be returned in a `Result`. + +use std::error::Error; +use std::fmt; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// This is required so that `CreationError` can implement `Error`. +impl fmt::Display for CreationError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let description = match *self { + CreationError::Negative => "number is negative", + CreationError::Zero => "number is zero", + }; + f.write_str(description) + } +} + +impl Error for CreationError {} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +fn main() -> Result<(), Box<dyn Error>> { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) } |