What does the `dyn` keyword mean in Rust types?
Hi! I started learning Rust and came across a strange thing. In some examples I see `Box`, and in others just `Box` or `&dyn Trait`. I'm trying to understand what exactly the `dyn` keyword does.
For example, I have this code:
```rust
trait Animal {
fn speak(&self);
}
struct Dog;
impl Animal for Dog {
fn speak(&self) {
println!("Woof!");
}
}
fn main() {
let pet: Box = Box::new(Dog);
pet.speak();
}
```
If I remove `dyn` and write just `Box`, the compiler gives an error: "the trait `Animal` cannot be made into an object". But I don't understand why this happens, and what `dyn` actually means. Is it some special type? Or a modifier? When should it be used, and when not?
Please explain.
No answers yet.
Log in to leave an answer