Trait Objects with Box dyn
Write a Rust function that uses Box
Trait objects (dyn Trait) enable dynamic dispatch in Rust, where the concrete method implementation is determined at runtime rather than compile time. Box
Dynamic dispatch with trait objects is a cornerstone of Rust's object-oriented programming patterns. Unlike generics (static dispatch) where a separate copy of the function is generated for each type, trait objects use a single code path with runtime dispatch. This reduces code size at the cost of a small runtime overhead from the vtable lookup.
Time complexity is O(1) for the vtable dispatch per method call. Space complexity is O(1) for the Box allocation plus the trait object's vtable pointer. The Box heap allocation is necessary because trait objects are unsized and must be behind a pointer.
Edge cases include strings other than "dog" or "cat" (return empty string or panic), ensuring the trait is object-safe (no generics in methods, no Self by value), and that the returned &'static str has a static lifetime.
Example Input & Output
Cat again
Final dog
Dog implementation
Dog again
Cat implementation
Algorithm Flow

Solution Approach
Best Answers
trait Animal {
fn speak(&self) -> &'static str;
}
struct Dog;
impl Animal for Dog {
fn speak(&self) -> &'static str { "Woof!" }
}
struct Cat;
impl Animal for Cat {
fn speak(&self) -> &'static str { "Meow!" }
}
fn solution(animal: &str) -> &'static str {
let a: Box<dyn Animal> = match animal {
"dog" => Box::new(Dog),
"cat" => Box::new(Cat),
_ => return "",
};
a.speak()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
