To change the number like this catches for example a wrong implementation only looking if right_result is zero, but not checking if we are doing a division.
fn eval(e: Expression) -> Result<i64, String> {
match e {
Expression::Op { op, left, right } => {
let left_result = eval(*left)?;
let right_result = eval(*right)?;
// Correct line commented out. (Or even better match inside the match below)
//if (right_result == 0) && (matches!(op, Operation::Div)) {
if right_result == 0 {
return Err(String::from("division by zero"));
}
Ok(match op {
Operation::Add => left_result + right_result,
Operation::Sub => left_result - right_result,
Operation::Mul => left_result * right_result,
Operation::Div => left_result / right_result
})
}
Expression::Value(value) => Ok(value),
}
}
to catch wrong
right == 0
checks.To change the number like this catches for example a wrong implementation only looking if
right_result
is zero, but not checking if we are doing a division.