Avatar ·

What is a trait object in Rust and how to create it?

Hello everyone! I've been learning Rust recently and trying to understand traits. I've read the documentation, but the concept of "trait object" remains unclear to me. Here's a simple trait I have: ```rust trait Animal { fn speak(&self); } struct Dog; impl Animal for Dog { fn speak(&self) { println!("Woof!"); } } struct Cat; impl Animal for Cat { fn speak(&self) { println!("Meow!"); } } ``` I want to make a vector that stores different animals — both Dog and Cat. But if I write `Vec`, the compiler complains that Animal is a trait, not a type. Online advice suggests using `Box`, but I don't understand what this `dyn` is and why it's necessary. Please explain: 1. What is a trait object in simple terms? 2. How does it work under the hood?