Boxes allow you to store data on the heap rather than the stack. What remains on the stack is the pointer to the heap data.
// Returns some struct that implements Animal, but we don't know which one at compile time.
fn random_animal(random_number: f64) -> Box<dyn Animal> {
if random_number < 0.5 {
Box::new(Sheep {})
} else {
Box::new(Cow {})
}
}
If box is anyways providing a pointer to the Heap data, and pointer size will be the same for both the struct on stack, why we can just return Box<Animal>
from this function?
I wish to know why I cannot write Box<Animal>
instead of Box<dyn Animal>
?