From fe0cebb8b9503e67dd7ac1d74b1980418326f865 Mon Sep 17 00:00:00 2001 From: Hariettemaina Date: Mon, 22 May 2023 17:05:01 +0300 Subject: [PATCH] using if and else to capture errors --- exercises/error_handling/errors4.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index 0efe8ccd..689fd294 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -1,7 +1,6 @@ // errors4.rs // Execute `rustlings hint errors4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -14,11 +13,17 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { - // Hmm...? Why is this only returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) + if value > 0 { + Ok(PositiveNonzeroInteger(value as u64)) + } else { + if value < 0 { + Err(CreationError::Negative) + } else { + Err(CreationError::Zero) + } + } } } - #[test] fn test_creation() { assert!(PositiveNonzeroInteger::new(10).is_ok());