What is the use of the "dyn" keyword?

I was learning about Traits.
When the "Rust by example" taught the use of the "dyn" keyword i got confused, as it seems unnecessary. https://doc.rust-lang.org/stable/rust-by-example/trait/dyn.html

If you remove the dyn keyword you get the same result. So why do I need it?

It exists to make the code easier to read. In the past, there was no dyn keyword, but it was introduced to make it clear when you are talking about a trait, and when you are talking about a concrete type.

Is it used so the compiler knows that a Trait is meant, or for other people?
And as for the compiler: By using dyn one can have Types and Traits with the same name. Is that correct?

It's for people. They occupy the same namespace. See playground.

2 Likes

Thank you very much!

It helps avoid a bunch of confusion about whether a type is a trait. Without dyn, it looks like a trait is a type, but it's not. No-dyn will probably be made to stop working at some point.

This way Trait will always be a trait, and you can think of both dyn and impl as "operators" that turn a trait into a type. (It's not technically precise, but that's ok.)

You can also read the RFC that introduced dyn:
https://rust-lang.github.io/rfcs/2113-dyn-trait-syntax.html

1 Like