5 ms·
> Rust actually supports most OOP features, with the main exception of implementation inheritance. I've tried some basic OOP. Fields from the base class need
by pizza234 4y ago
> Rust actually supports most OOP features, with the main exception of implementation inheritance.
I've tried some basic OOP.
Fields from the base class need to be redefined in each child, and making shared methods private require an ugly workaround. Both concepts are very basic OOP concepts, not advanced or inherently/tendentially dangerous, and the results is that even basic Rust OOP requires a lot of boilerplate. It's workaroundable with macros if one wants, although they have some limitations, and I guess this is the reason why the macro approach is not widespread.
Some devs use composition to emulate it, but the result is another form of boilerplate (very noisy builder patterns).
Regarding "non-basic" OOP features, I remember that Rust GUI framework programmers uniformly complain about Rust not being appropriate to translate the OOP hierarchies typically used in GUI frameworks, so the gap is significant (this is not inherently bad; not supporting OOP can be a respectable choice, but matter of factually, this does create a gap in some cases).
- zozbot234 4y agoRust itself does not have much support for delegation (the building block for the features you're referring to) since it's pretty much syntactic sugar anyway, but you can use crates like 'ambassador' to provide that.
- glandium 4y agoYou can define a field with the type of the base class in the subclass, and impl Deref for SubClass, with Target = BaseClass.
- cylon13 4y agoYou can, but the docs for Deref beg you not to use Deref for types that aren’t smart pointers because of how confusing and surprising the results can be to an unfamiliar reader of the code.
- grey-area 4y agoDoes OOP require inheritance?
- pjmlp 4y agoKind of, it needs the ability to express polymorphism and extend concepts. Now how that is done is practice, can be done in various ways. Class inheritance, which is what many think of. Interface inheritance or conformance, which is available in many languages via traits, patterns, data classes, functors, or other names, and OS ABIs like COM. Prototype inheritance, clone a instance and monkey patch in place (like SELF) Via composition and delegation for not handled messages. Then many languages offer a combination of those approaches.
- anon291 4y agoThe idea of object inheritance is silly. If you need a 'base' class A for data type B just do struct B { a: A }