google / comprehensive-rust

This is the Rust course used by the Android team at Google. It provides you the material to quickly teach Rust.
https://google.github.io/comprehensive-rust/
Apache License 2.0
27.96k stars 1.67k forks source link

Change tests for pattern-matching exercise #2463

Closed mo271 closed 3 days ago

mo271 commented 4 days ago

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.

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),
    }
}