rustlings/exercises/13_error_handling/errors4.rs

40 lines
832 B
Rust
Raw Normal View History

2024-07-04 12:38:35 +01:00
#![allow(clippy::comparison_chain)]
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
2024-06-26 14:54:18 +01:00
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
2024-06-26 14:54:18 +01: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 22:34:27 +01:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_creation() {
assert_eq!(
2024-06-26 14:54:18 +01:00
PositiveNonzeroInteger::new(10),
Ok(PositiveNonzeroInteger(10)),
);
assert_eq!(
PositiveNonzeroInteger::new(-10),
2024-04-17 22:34:27 +01:00
Err(CreationError::Negative),
);
2024-06-26 14:54:18 +01:00
assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero));
2024-04-17 22:34:27 +01:00
}
}