Hi I am learnig rust and doing the excercise rustlings/itertors3.rs
My first implementation of fn divide
not behaves as I expected. Could Someone explain me why?
My first attempt was:
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
let res = a.checked_div(b).ok_or(DivisionError::DivideByZero)?;
match res*b {
a => Ok(res),
other => Err(DivisionError::not_evenly_dividable(a, b))
}
}
But this gives a false positive. This works:
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
let res = a.checked_div(b).ok_or(DivisionError::DivideByZero)?;
match a%b {
0 => Ok(res),
other => Err(DivisionError::not_evenly_dividable(a, b))
}
}
Why?