{{#include exercise.rs:solution}}- Pattern Matching: We use
matchto handle the different variants of theExpressionenum. This ensures we cover all possible cases. - Destructuring: The pattern
Expression::Op { op, left, right }destructures theOpvariant, giving us access to its inner fields. - Recursion: Since
Expressionis a recursive data structure,evalis a recursive function. We calleval(*left)andeval(*right)to compute the values of the sub-expressions. - Smart Pointers (
Box): Theleftandrightfields are of typeBox<Expression>.Boxputs the value on the heap. The*operator dereferences the box, moving the innerExpressionout so it can be passed by value to the recursiveevalcalls.
Details
- Mention that
Boxis necessary becauseExpressionhas infinite size otherwise (it contains itself).Boxprovides a fixed size (pointer size) for the recursive fields. - Discuss integer division behavior (truncation) for
Operation::Divsince we are using integers.