Solution

// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0

/// An operation to perform on two subexpressions.
#[derive(Debug)]
enum Operation {
    Add,
    Sub,
    Mul,
    Div,
}

/// An expression, in tree form.
#[derive(Debug)]
enum Expression {
    /// An operation on two subexpressions.
    Op { op: Operation, left: Box<Expression>, right: Box<Expression> },

    /// A literal value
    Value(i64),
}

#[derive(PartialEq, Eq, Debug)]
struct DivideByZeroError;

fn eval(e: Expression) -> Result<i64, DivideByZeroError> {
    match e {
        Expression::Op { op, left, right } => {
            let left = eval(*left)?;
            let right = eval(*right)?;
            Ok(match op {
                Operation::Add => left + right,
                Operation::Sub => left - right,
                Operation::Mul => left * right,
                Operation::Div => {
                    if right == 0 {
                        return Err(DivideByZeroError);
                    } else {
                        left / right
                    }
                }
            })
        }
        Expression::Value(v) => Ok(v),
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_error() {
        assert_eq!(
            eval(Expression::Op {
                op: Operation::Div,
                left: Box::new(Expression::Value(99)),
                right: Box::new(Expression::Value(0)),
            }),
            Err(DivideByZeroError)
        );
    }

    #[test]
    fn test_ok() {
        let expr = Expression::Op {
            op: Operation::Sub,
            left: Box::new(Expression::Value(20)),
            right: Box::new(Expression::Value(10)),
        };
        assert_eq!(eval(expr), Ok(10));
    }
}
  • Result Return Type: The function signature changes to return Result<i64, DivideByZeroError>. This explicit type signature forces the caller to handle the possibility of failure.
  • The ? Operator: We use ? on the recursive calls: eval(*left)?. This cleanly propagates errors. If eval returns Err, the function immediately returns that Err. If it returns Ok(v), v is assigned to left (or right).
  • Ok Wrapping: Successful results must be wrapped in Ok(...).
  • Handling Division by Zero: We explicitly check for right == 0 and return Err(DivideByZeroError). This replaces the panic in the original code.
  • Mention that DivideByZeroError is a unit struct (no fields), which is sufficient here since there’s no extra context to provide about the error.
  • Discuss how ? makes error handling almost as concise as exceptions, but with explicit control flow.