Trait Objects memory diagram uses different order for different cells
https://google.github.io/comprehensive-rust/generics/trait-objects.html has this diagram:
https://github.com/google/comprehensive-rust/blob/c212a473ba4d060b209b654c0dd403328d6e137f/src/generics/trait-objects.md?plain=1#L41-L67
Quoting https://doc.rust-lang.org/reference/types/trait-object.html
Each instance of a pointer to a trait object includes:
- a pointer to an instance of a type T that implements SomeTrait
- a virtual method table, often just called a vtable, which contains, for each method of SomeTrait and its supertraits that T implements, a pointer to T's implementation (i.e. a function pointer).
It seems the diagram here draws one object as (instance, vtable) and the second as (vtable, instance). Consistency would help, and based on https://doc.rust-lang.org/reference/types/trait-object.html it seems (instance, vtable) is the safer assumption.
Also, I think the vtable pointer should point to e.g. <i32 as Display>, not just to the ::fmt method.
The layout of wide pointers (or references) isn't guaranteed generally, nor guaranteed to be the same between different types. That is, they're not guaranteed to be consistent. (The order of Vecs fields isn't guaranteed either.)
The vtable holds other omitted things too; perhaps just note this is meant to give the general idea.
If you don't want to imply a specific memory layout, maybe move the diagram away from showing things as "little arrays" and e.g. use labeled fields as origins of the arrows.
Hi @tv42 and @QuineDot,
It seems the diagram here draws one object as (instance, vtable) and the second as (vtable, instance).
That is certainly not on purpuse, thanks for catching this :smile:. Would you care to submit a PR to make the arrow consistent?
The vtable holds other omitted things too; perhaps just note this is meant to give the general idea.
Yes! This is meant to be very "symbolic". The diagram just gives me something to point to during class and I hope it can help convey a useful mental model to the students.
move the diagram away from showing things as "little arrays" and e.g. use labeled fields as origins of the arrows.
It's very tricky to draw nice diagrams which are both correct and informative. Here, I tried to convey that the Vec<Box<dyn Display>> contains
- Double-width pointers, e.g., the two
o othings inside the vector element boxes - One pointer is to data
- The other pointer is to code
I considered adding more i32 or &str elements so that I could show that the pointers to the code is the same for those elements. However, I think the diagram is already quite busy so I shied away from that idea again. But it's something I would point out during class while showing the diagram.
I would be happy to hear if there are other points about trait objects which we can illustrate with these diagrams.
This got fixed in #169.