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 16:54:18 +03:00
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
2024-06-26 16:54:18 +03: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-18 00:34:27 +03:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_creation() {
assert_eq!(
2024-06-26 16:54:18 +03:00
PositiveNonzeroInteger::new(10),
Ok(PositiveNonzeroInteger(10)),
);
assert_eq!(
PositiveNonzeroInteger::new(-10),
2024-04-18 00:34:27 +03:00
Err(CreationError::Negative),
);
2024-06-26 16:54:18 +03:00
assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero));
2024-04-18 00:34:27 +03:00
}
}