Sometimes, the Rust compiler cannot determine the size of a trait object at compile time. For example, if a function returns a trait object based on a condition, in such cases, impl Trait is not going to work. This is because the size of the trait object is not known at compile time. In such cases, you can use Box<dyn Trait> to return a trait object.
Box<T> lets you allocate memory on the heap and store the value of T in that memory. Box<dyn Trait> is a trait object that allows you to store a value of any type that implements Trait in the heap.
This is called dynamic dispatch because the method to call is determined at runtime, not at compile time. This is in contrast to static dispatch, where the method to call is determined at compile time.
Your Task
You need to define a function that returns a Box<dyn Speakable> based on a condition.
Here is what you need to do:
- Define the
Speakabletrait with a methodspeakthat returns aString. - Define a struct
Dogwith two fields:nameandbreed, both of typeString. - Implement the
Speakabletrait forDogto return a stringWoof. - Define a struct
Robotwith two fields:modelandpurpose, both of typeString. - Implement the
Speakabletrait forRobotto return a stringBeep boop. - Finish the function
get_speakerthat takes a&strparameter and returns either aDogor aRobotbased on the parameter. - The parameter can either be
dogorrobot.
pub fn get_speaker(kind: &str) -> Box<dyn Speakable> {match kind {"dog" => {// Return a Dog instance here}"robot" => {// Return a Robot instance here}_ => panic!("Unknown speaker type"),}}// Example usagepub fn main() {let dog_speaker = get_speaker("dog");println!("{}", dog_speaker.speak()); // Expected output: Wooflet robot_speaker = get_speaker("robot");println!("{}", robot_speaker.speak()); // Expected output: Beep boop}