With composition over inheritance in Rust, how does one implement shared state to go with shared behaviour?

There was a draft RFC for 'fields in traits'. It's been shelved for now, AFAIK, since there's a large amount of accepted RFCs that haven't been implemented yet that take priority. For now, the only way to model this would be to make functions in the inheriting trait that return concrete types and have the implementing type work with those.

Final implementations in rust can be done by making a public trait that inherits an empty private trait (take a look here: Future proofing - Rust API Guidelines).

Overall, however, you need to stop looking at ways to use rust to model an OOP structure. Just because your project can be modelled using OOP doesn't mean it's the optimal approach. And if you're looking for ways to do OOP in rust, you'll sometimes ignore unique (as well as not so unique) solutions that rust can provide to make your code clean and easy to maintain.

Awhile ago, back when I was a much worse programmer, I had to spend a few months learning how to do OOP code well. I did so through a few stack exchange questions (link, link). The most useful answers that I got there talked primarily to entirely about how to do OOP right. Maybe I need more advice of this angle, but for Rust.

I use a very simple macro for this sort of thing to make decorators at the type level.

The rule is that the decorating type has a member (base : T) that implements the default behavior.
(Base in my program refers to something like a database, but it works just as well for "base class").

So then when I declare a "subclass" (decorator), I use this macro to explicitly list and implement in the "inherited methods".

https://github.com/tangentstorm/bex/blob/7434cac1e43879675c4e97c5c73d1a2efa7a70e8/src/base.rs#L77

A tiny example usage is just below. (This software deals with boolean expressions, and this implements a single simplification rule for "AND" operations)

https://github.com/tangentstorm/bex/blob/7434cac1e43879675c4e97c5c73d1a2efa7a70e8/src/base.rs#L100

Thanks for your post, btw... I actually decided to implement this while writing an initial draft of an answer to your question. :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.