Back to questions
JuniorTheoryCommon
What does the program print?
enum Shape {
Rect(u32, u32),
Square(u32),
}
fn main() {
let shapes = [Shape::Rect(3, 4), Shape::Square(5)];
match shapes[0] {
Shape::Square(a) => println!("{}", a * a),
Shape::Rect(w, h) => println!("{}", w * h),
}
}12
- Expecting
9: a pattern checks the variant before it binds anything, soShape::Square(a)does not fitShape::Rect(3, 4), and theRect(w, h)arm runs instead. - Expecting an error because
wandhare never declared: a pattern declares the variables it names and fills them with the variant's data.
- What does the program print if it matches
shapes[1]instead? - What happens if you delete the
Shape::Squarearm?