rustlings/exercises/error_handling/result1.rs
2020-12-06 16:32:06 +01:00

38 lines
1,013 B
Rust

// result1.rs
// Make this test pass! Execute `rustlings hint result1` for hints :)
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
match value {
value if value < 0 => Err(CreationError::Negative),
0 => Err(CreationError::Zero),
_ => Ok(PositiveNonzeroInteger(value as u64)),
}
/*if value < 0 {*/
//return Err(CreationError::Negative);
//} else if value == 0 {
//return Err(CreationError::Zero);
//}
/*Ok(PositiveNonzeroInteger(value as u64))*/
}
}
#[test]
fn test_creation() {
assert!(PositiveNonzeroInteger::new(10).is_ok());
assert_eq!(
Err(CreationError::Negative),
PositiveNonzeroInteger::new(-10)
);
assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0));
}