rustlings

solving rustlings ft. dracuxan
git clone [email protected]:dracuxan/rustlings.git
Log | Files | Refs

errors4.rs (1288B)


      1 use core::cmp::Ordering;
      2 
      3 #[derive(PartialEq, Debug)]
      4 enum CreationError {
      5     Negative,
      6     Zero,
      7 }
      8 
      9 #[derive(PartialEq, Debug)]
     10 struct PositiveNonzeroInteger(u64);
     11 
     12 impl PositiveNonzeroInteger {
     13     fn new(value: i64) -> Result<Self, CreationError> {
     14         // TODO: This function shouldn't always return an `Ok`.
     15         // Read the tests below to clarify what should be returned.
     16 
     17         // if value > 0 {
     18         //     Ok(Self(value as u64))
     19         // } else if value < 0 {
     20         //     Err(CreationError::Negative)
     21         // } else {
     22         //     Err(CreationError::Zero)
     23         // }
     24 
     25         match value.cmp(&0) {
     26             Ordering::Less => Err(CreationError::Negative),
     27             Ordering::Equal => Err(CreationError::Zero),
     28             Ordering::Greater => Ok(Self(value as u64)),
     29         }
     30     }
     31 }
     32 
     33 fn main() {
     34     // You can optionally experiment here.
     35 }
     36 
     37 #[cfg(test)]
     38 mod tests {
     39     use super::*;
     40 
     41     #[test]
     42     fn test_creation() {
     43         assert_eq!(
     44             PositiveNonzeroInteger::new(10),
     45             Ok(PositiveNonzeroInteger(10)),
     46         );
     47         assert_eq!(
     48             PositiveNonzeroInteger::new(-10),
     49             Err(CreationError::Negative),
     50         );
     51         assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero));
     52     }
     53 }