What is the use of Rust's impl trait for dyn trait? Are there any practical use cases?

Rust allows developers to write code like this:

trait A {}
trait B {}
impl A for dyn B {}

However, I'm not sure what the practical use of this language feature is.
Does anyone have small examples or practical scenarios they can share?

In your code snippet, B is a trait object. These are useful if we don't know the exact type of object that will be passed to us until runtime, but we want to guarantee we can call certain methods on it.

An example of where this is used in the standard library is the implementation of the Debug trait for trait objects implementing the Any trait.

2 Likes

it's not some "special" language feature, besides the fact dyn SomeTrait is just a type (albeit unsized, i.e. it doesn't satisfy the Sized bound). you can implement any traits on any types, as long the coherence (the orphan rule) is not violated.

1 Like

Here's another practical example.

It's not a separate feature. What's the practical use of implementing a trait for a type?

1 Like

A case in my project. I built a tiny virtual DOM library and abstract "effect" which described with some data in struct. I could declare the behaviors of "effect" with trait. A component might contain multiple effects and each could have its own data for describing effect parameters.

So I have a vector holding component effects, and internally I use dyn trait object to put effect params inside this vector, meanwhile each of them implements the RespoEffect trait.

so, sharing behaviors, each has its own struct, stored in some vector.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.