Adding regular functions to trait objects

Hey folks,

I've learned that a trait object is a type which has been coerced into a trait object plus it's vtable. But now I've found out that you can also add regular functions to trait objects eg via impl dyn T, see here. Somehow this doesn't suit for me in the concept of a trait object in my mind. Does Rust add these functions to values of specific types which it coerces into trait objects or where are they lying around in memory?

Regards
keks

Why would that be needed? dyn Foo is concrete type, like int or String. It works exactly like any other concrete type.

No, impl dyn Trait is the same as impl AnyOtherType. When you already have a value of type dyn Trait, the compiler will allow you to call these methods on it. This has nothing to do with the vtable or dynamic dispatch.

2 Likes

I see! Makes sense to me. Thanks! :slight_smile:

... so eg here b.demo(); gets dynamically dispatched and b.demo2(); statically, right?

Yes.

1 Like

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.