I am aware of options of trait objects and enum to store different types of objects in a collection, but in both cases, there is a penalty on the runtime efficiency (if I understand it well). In the trait
's case, there must be a dynamic dispatch (dyn
) and in the enum
, all possibilities are checked at runtime (just like a switch). Right? There is a loss of efficiency in both cases, so I was wondering if there is any right way of doing it without that loss.
Using the example in Listing 17-9, for instance:
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No"),
],
}),
Box::new(Button {
width: 50,
height: 10,
label: String::from("OK"),
}),
],
};
In this case, at compile-time, I know that the vector has those instances, so I don't understand the need for that loss.
How is that different from having a vector of strings? They may also have different sizes.