rustlings/exercises/13_error_handling/errors4.rs

38 lines
795 B
Rust
Raw Normal View History

#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
2024-06-26 09:54:18 -04:00
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
2024-06-26 09:54:18 -04:00
fn new(value: i64) -> Result<Self, CreationError> {
// TODO: This function shouldn't always return an `Ok`.
Ok(Self(value as u64))
}
}
fn main() {
// You can optionally experiment here.
}
2024-04-17 17:34:27 -04:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_creation() {
assert_eq!(
2024-06-26 09:54:18 -04:00
PositiveNonzeroInteger::new(10),
Ok(PositiveNonzeroInteger(10)),
);
assert_eq!(
PositiveNonzeroInteger::new(-10),
2024-04-17 17:34:27 -04:00
Err(CreationError::Negative),
);
2024-06-26 09:54:18 -04:00
assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero));
2024-04-17 17:34:27 -04:00
}
}