Code Logo

Trait Objects with Box dyn

Published at25 Jul 2026
Rust Functions Hard 0 views
Like0

Write a Rust function that uses Box where Animal is a trait with a speak() method returning &str. Two structs Dog and Cat implement Animal. The function takes a string "dog" or "cat" and returns the appropriate animal's sound using dynamic dispatch through Box.

Trait objects (dyn Trait) enable dynamic dispatch in Rust, where the concrete method implementation is determined at runtime rather than compile time. Box is a heap-allocated trait object. The vtable (virtual method table) stored in the trait object pointer enables calling the correct speak() implementation based on the actual type.

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

Example 1
Input
"cat"
Output
"Meow!"
Explanation

Cat again

Example 2
Input
"dog"
Output
"Woof!"
Explanation

Final dog

Example 3
Input
"dog"
Output
"Woof!"
Explanation

Dog implementation

Example 4
Input
"dog"
Output
"Woof!"
Explanation

Dog again

Example 5
Input
"cat"
Output
"Meow!"
Explanation

Cat implementation

Algorithm Flow

Recommendation Algorithm Flow for Trait Objects with Box dyn
Recommendation Algorithm Flow for Trait Objects with Box dyn

Solution Approach

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()
}

Best Answers

rust - Approach 1
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()
}