#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm... Why is this always returning an Ok value?
if value == 0 {
Err(CreationError::Zero)
} else if (value < 0) {
Err(CreationError::Negative)
} else {
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));
}
The PartialEq
trait in Rust is used to enable equality comparisons (==
and !=
) on types. In the code snippet you've shared, PartialEq
is derived for both the CreationError
enum and the PositiveNonzeroInteger
struct to allow for these equality comparisons, which are particularly useful and necessary in the context of testing.
Deriving PartialEq
for CreationError
and PositiveNonzeroInteger
is necessary for enabling equality comparisons in tests, which is a common practice to check if the code behaves as expected, especially when dealing with error handling and custom types in Rust.