Going through rustlings for the first time
at main 43 lines 1.0 kB view raw
1use std::cmp::Ordering; 2 3#[derive(PartialEq, Debug)] 4enum CreationError { 5 Negative, 6 Zero, 7} 8 9#[derive(PartialEq, Debug)] 10struct PositiveNonzeroInteger(u64); 11 12impl PositiveNonzeroInteger { 13 fn new(value: i64) -> Result<Self, CreationError> { 14 // TODO: This function shouldn't always return an `Ok`. 15 match value.cmp(&0) { 16 Ordering::Greater => Ok(Self(value as u64)), 17 Ordering::Equal => Err(CreationError::Zero), 18 Ordering::Less => Err(CreationError::Negative), 19 } 20 } 21} 22 23fn main() { 24 // You can optionally experiment here. 25} 26 27#[cfg(test)] 28mod tests { 29 use super::*; 30 31 #[test] 32 fn test_creation() { 33 assert_eq!( 34 PositiveNonzeroInteger::new(10), 35 Ok(PositiveNonzeroInteger(10)), 36 ); 37 assert_eq!( 38 PositiveNonzeroInteger::new(-10), 39 Err(CreationError::Negative), 40 ); 41 assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero)); 42 } 43}