Sharing getters among structs

As a preamble, I know the question of inheritance in Rust has been asked a lot of times, and that one should not try to force an OOP design in Rust.

I have some structs that share common fields. I would like to avoid having to write getters for every of these common fields in every impl block that I write for each of these structs. Since there are common fields, I tried to implement a trait that implement those getters and to implement it to an Enum whose variants are the structs that share these common fields. I have a small working example here: Playground. However, the common fields can't be accessed in the implementation of the trait.

My goal is to avoid having redundant code by re-writing in every impl blocks the same getters.

Do you know any way to implement getters for common fields between different structs?

Well, there is a crate getset which allows you to use macros to generate getters and setters. This should considerably reduce your effort.

Is there any situation where you want the user to be able to modify the object, but not have the ability to modify these fields? If not, you should consider making the fields public instead of writing getters.

Alternatively, you can define the common fields as a separate struct type that's included as a single field in each of the specialized structs, which only requires you to write a single getter for each.

3 Likes

This sounds right.

The OP’s design is still an inheritance pattern. Inheritance can always be replaced with composition and that’s what’s described here.

1 Like

If your usage of these object is quite contained in the code, you could consider making it more data-oriented. Sure it has some other side effects but might be worth considering.
you group your members in separate lists and use something lightweight that represents as a key for your instances.
i created a quick example to show what i mean Rust Playground

you could come up with something smart to represent the keys. Also if you want something a bit more fancy as HashMaps you could consider slotmaps slotmap - Rust

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.