When is worth to define a Trait?


#1

I have a question regarding how to structure my code. Right now I have something like this:

enum Kind {
   A,
   B,
   C,
   D,
}

struct MyStruct {
    x: i32,
    y: i32,
    kind: Kind
}

Inside most of the implemented functions for MyStruct I have a match of kind and do the right thing in each case. However, I could do it differently: define a trait and create MyStructA, MyStructB, etc implementing that trait.

The only advantage that I can see for the second one is the ability to extend it. But in this particular case, from the design point of view, there are no other kinds possible except those 4.

So, what are the pros and cons in each case?


#2

In general I would say use a trait if it’s likely to be a compile-time constant in most code paths, and use an enum if runtime polymorphism is required, but there are exceptions both ways; try switching if it gets unergonomic.