Best practice for fields inheritence in Rust


#1

Hi, so I wanted to hear what are the best practices for structs, where there is a “common” struct or a bunch of fields which exist in any other in the project and well don’t want to copy them. Is it better to just write a macro for defining them? Or should I have a BaseStruct and than each other struct has that as a field? What do people consider a good practice on this one?


#2

Is it just data or do you have functions/methods associated with it?

Personally, I’d define a single struct and reuse it if I can.


#3

It’s mainly data with maybe 1-2 common methods on it.


#4

And what about impl requirements on it? Eg would Debug/Display/Copy?/Clone?/Default? be the same for all uses?

If so, I don’t see any reason to not stick with a single shared type. You can macro generate unique ones but then you’ll have code/metadata/debuginfo/etc bloat for no good reason that I can see.


#5

I don’t think I want Copy… but yeah the other standard Traits are there.

I don’t say that it is a bad choice, I’m just looking for opinions and yours noted on +1 for Shared Struct. :slight_smile:


#6

I meant as long as all uses of the struct have the same requirements, whatever those may be.

Oh yeah - I’m just stating my opinion and rationale :slight_smile: Maybe someone can think of a good argument for other approaches.