10.8 Enums in Collections and Functions
Even though enum variants may contain different data with varying sizes, they are considered a single type.
10.8.1 Storing Enums in Collections
Example:
let messages = vec![
Message::Quit,
Message::Move { x: 10, y: 20 },
Message::Write(String::from("Hello")),
];
for msg in messages {
msg.call();
}
- Homogeneous Collection: All elements are of type
Message
. - No Boxing Needed: Unlike trait objects, no heap allocation is required for polymorphism.
10.8.2 Passing Enums to Functions
Functions can accept enums as parameters and handle all variants.
Example:
fn handle_message(msg: Message) {
msg.call();
}
fn main() {
let msg = Message::ChangeColor(255, 0, 0);
handle_message(msg);
}