Visualizing Rust's Vtables: How dyn Trait Works In Memory

Visualizing Rust's Vtables: How dyn Trait Works In Memory

A hands-on exploration of Rust's dynamic dispatch, comparing it with C++'s virtual functions and CRTP. The author dives into memory layouts, wide pointers, and zero-sized types, showing how Rust's vtable is external to the object and chosen at the call site. Includes code examples and visualizations.

In Rust, the choice is made at the call site. Circle is just Circle, it knows nothing about dispatch.
  1. tialaramex

    This has a section on Object Safety, I checked and the article was written this week, but "Object Safety" is a confusing name for this idea, and so for a little while now Rust calls this idea "dyn compatibility" because the most important thing you're getting if a trait is "dyn compatible" is that you can use "dyn Trait" - https://doc.rust-lang.org/1.98.1/reference/items/traits.html...

    That link more comprehensively explains the rules too.

    [Edit: Realized the end of the article explains this, the author began writing it months ago, likely before they read about the improved "dyn compatibility" naming]

  2. evmar

    In my own journey of discovery I found https://cheats.rs/ very helpful, and in particular its "memory layout" section has visualizations. (No affiliation with the site, just a happy reader!)

  3. Panzerschrek

    > A trait must follow so-called object safety rules to be used as a trait object

    This seems for me to be a major design flaw of Rust. It tries to repurpose traits for dynamic polymorphism, even if this doesn't fit perfectly. C++ is more honest, it has two separate mechanisms for static polymorphism (templates) and dynamic polymorphism (inheritance).

  4. Panzerschrek

    I once faced a tricky bug involving fat pointers (containing virtual tables) in Rust. Two such pointers may be distinct, even if they reference to the same object, because (for some reason) the compiler may create two (or even more) copies of the virtual functions table and use them in different places.

  5. returningfory2

    Very nice. As a follow up would be interesting to also reverse engineer the structure of the vtable itself. I guess it’s a list of pointers to the method implementations?

More from this day

2026-09-05