Hacker News new | ask | show | jobs
by naasking 2963 days ago
I think your explanation of static and dynamic dispatch is either wrong, or incredibly confusing.

The offset of the function pointers is always statically known for a given trait/interface type, it's just the actual vtable instance that may not be known, ie. the concrete type implementing that trait/interface. A statically known vtable instance that can be inlined/monomorphized is static dispatch, and if it's not known at compile-time it must be dynamically dispatched.

1 comments

I don't understand what's so confusing about it. GP says

"calling the trait method requires a dynamic lookup to find the method on the boxed object"

It sounds like all you want to say is

"calling the trait method requires a dynamic lookup to find [the vtable instance, which is then used to find] the method on the boxed object"

That's not the clarification I was making. For instance, I simply can't interpret this line from the original post as anything but incorrect:

> then the function pointer will always be in the same place on the object in memory (static dispatch)

As I said, static vs. dynamic dispatch is about knowledge of the vtable instance, not about the offset into the object or the vtable. All of the offsets are always known statically, it's merely what you're indexing into that may or may not be known statically.

Maybe I'm being pedantic, but I've found that there's a lot of misunderstanding surrounding static vs. dynamic dispatch.

I see. Makes sense. It might help to show what the representation in memory of a trait object is. (I'm assuming there's a type for it somewhere in rustc, but I don't know where offhand.)