OOP how to override



I am new to the Rust language.

I am disappointed by Rust OOP capabilities. It seems you can no longer say:

struct A: B; // No inheritance for struct: error: virtual structs have been removed from the language

Does this mean that I cannot override a method from B in A?

Ares these limitations present because something is not yet implemented?


TLDR: Learn to love traits, because they’re all you’ve got.

Rust eschews traditional OOP constructs in favour of traits.

There is no struct inheritance. You can have one trait inherit from another (trait A: B), although the practical effect is merely that it requires anything that implements A to also implement B. You cannot (in general) downcast or sidecast; you can turn an &A into a &B, but you can’t go back, and you can’t turn a &Trait into a &ConcreteType.

There is one exception to the above bits about casting: Any. However, it only allows you to downcast to the exact type it was created from.

As for overriding, you can define a “default implementation” of methods in a trait, then override those in a concrete implementation, but that’s it.

All of the above is by design.

Now, that said, there is a desire for some kind of “virtual structs” support, primarily driven by the needs of Servo. It’s just that, at present, no one is entirely sure how this should be done. It seems unlikely that Rust will just get classes; the desire is to provide the necessary building blocks to get what you need.


In case it is helpful (it was for me):


Thank you. I knew that. I does not change the fact that I cannot override a method with the exception of changing a method provided by a trait but with no possibility of calling back that method if I decide to override it.

I guess I’ll have to use external functions and use them for composition.


Hope this will help you…OOP Basics