Simulating inheritance by composition

I tried to write some generic code, which is similar to inheritance, but more efficient, and now have an idea how to simulate inheritance in current rust (preferably with using specialization). I wrote a text about that here and some example code here.

This approach still has some problems, but it may be pretty powerful, when doing it correctly. I’m not sure, if language updates would be needed in order to make this pattern work good. I’m interested, if someone has better ways to achieve such a design. If done correctly, this really could help to simplify something, I’m working on, but I also don’t know yet, if just defining the structs, I need in a special case, would be more usable, even if this would result in code duplication.

rustc uses Deref throughout the codebase to allow you to call methods from the composed ADT directly. In the linked code, if you have an IndexBuilder called ib, you can call ib.position(), for example.

Using Deref and DerefMut was my first design. The definition of Inherit and InheritMut are almost copied from them. But the automatic dereferencing is not powerful enough for most applications. It does not work correctly with traits. I defined the methods for all my methods, which just call the same method of he dereferenced object, and got different results. An example, when this does not work correctly, is when I have some type T, which derefs to U, which both implement two traits A and B. A method of trait A calls a method of trait B. But when I just redefine the trait B for type T, and then call the the method of trait A, it first dereferences to type U and then calls the method of trait B, that was implemented for U, and not the overridden version of type T, so this does not work as expected. Additionally there is a bug(?) in dereferencing, when there are multiple specializations of the same generic trait defined for different versions of deref, as I showed in this issue, which also works correctly with default methods. But it’s probably worth looking at this approach another time.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.