rustlings

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

errors4.rs (939B)


      1 use std::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         match value.cmp(&0) {
     15             Ordering::Less => Err(CreationError::Negative),
     16             Ordering::Equal => Err(CreationError::Zero),
     17             Ordering::Greater => Ok(Self(value as u64)),
     18         }
     19     }
     20 }
     21 
     22 fn main() {
     23     // You can optionally experiment here.
     24 }
     25 
     26 #[cfg(test)]
     27 mod tests {
     28     use super::*;
     29 
     30     #[test]
     31     fn test_creation() {
     32         assert_eq!(
     33             PositiveNonzeroInteger::new(10),
     34             Ok(PositiveNonzeroInteger(10)),
     35         );
     36         assert_eq!(
     37             PositiveNonzeroInteger::new(-10),
     38             Err(CreationError::Negative),
     39         );
     40         assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero));
     41     }
     42 }