Traits vs interfaces and abstract classes

What is difference between Rust Traits and Java interfaces or C++ abstract classes? Difference is that structure can be extended later by trait in other module? How in this case call method, which is from trait?

1 Like

Abstraction without overhead: traits in Rust | Rust Blog should get you going.


Nice : "impl Hash for bool". This means that I can write trait for converting string to WCHAR* (C-style) instead of usual function and implementing this trait to string.

low level difference:-

For C++ classes (including abstract classes) the vtable pointer is embedded in the class/struct instance; the whole object can be referenced by one pointer.

by contrast, when rust uses runtime dispatch, it passes interfaces around as a pair of pointers (the vtable, and the data). The underlying data-structure does not need to know what interfaces are implemented for it or being used at any time, or if it's being used for compile or runtime dispatch at all.

The two schemes have different strengths and weaknesses, but rusts overall simplification is in re-using the traits for generic type bounds (which C++ will do with a completely new feature, 'concepts'), and it's easier to extend/decouple.

When there's only one pointer to something (e.g. trees) they should be the same, and rust has the advantage that you're not bloating the structure in the cases where you just want static dispatch. But other times (graph structures?), you're paying with heavier pointers. ( I would guess just passing the pair around most of the time doesn't matter , the effect on pointers in memory is probably most significant.. but thats just a guess, if anyone has data?)

C++ does something more convoluted for multiple inheritance if you want to implement multiple 'interfaces' in the same class.

1 Like

There was a good (relatively) short blog on this earlier this year: Exploring Dynamic Dispatch in Rust

1 Like