Traits and classes?


#1

Hello everybody

I am not a pure programmer in a sense that I am mainly programming for applied mathematics.
However I have a question about traits and classes. Why keeping classes if the language implement traits proprely?

Best regards

Sebastien


#2

This appears only tangentially related to Rust, but I’ll try to answer it in the general sense:

  • traits allow to bind behaviour to types. They don’t have structure themselves, but the types they apply to very well may have. They don’t really do inheritance (except for specialization or generic bounds).
  • classes (as in most object systems) bind structure and behaviour together. Depending on the object system, you can inherit once or many times (which gives rise to interesting problems like the aptly named Diamond), or inherit only the interface (which requires implementation). There has been a long standing argument that this duality (mixing structure + behaviour) has severe downsides. Rust really doesn’t have classes, only separate structure (as in struct, enum, tuples, etc.) and traits that operate on them.

#3

If Rust does not really have classes and separate struct and implementation (some kind of vtable), why keeping the notation charge of trait (T: Fooable followed by x: T for example instead of just x: fooable)?
Could not be more simple to consider all type like traits?


#4

types are in fact a superset of traits: they also contain structs, enums, tuples, arrays, nums (as in i32), etc. Btw. a RFC for adding (some types of) inheritance to Rust is currently being worked on by mathieum.

Note also that trait objects are known only by their trait bound and thus have no (known) size. Which is why a Vec<T> does not work in the general case, it reqires T to be bound by Sized. Also traits don’t necessarily require dynamic dispatch via vtable – that’s just an implementation detail of dynamic polymorphism and may be compiled away if the compiler determines that there is only one implementation used.