Impl dyn Trait?

What does impl dyn Trait mean? Does it mean something? What should I read?


dyn Trait is a type, so it can be used wherever we need the type. This includes implementing methods on it, so that it can be used only on the trait object, not on the every type implementing this trait.



Is any point of implementing method on impl Trait instead of implementing the on the trait itself?

Is there any other usefulness of impl Trait for dyn?

Methods directly in the trait must be implemented by each downstream type that implements the trait, and even if you provide a default implementation, it can be overridden. This is not so for impl dyn Trait { blocks.

You can find some examples of this on the Any trait. The trait provides only the type_id method, but there are various other methods that are implemented based on the type_id method.

Note also that methods defined on dyn Trait are normally not accessible on other types that implement the trait unless you first create a reference and cast it to a dyn reference, e.g.

(&mut my_struct as &mut dyn MyTrait).my_trait_impl_method();

@Cerber-Ursi @alice thank you for explanation. It makes sense.

You can find some examples of this on the Any trait
Any specific example?

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.