Struct->Trait/Enum Transition

⚓ Rust    📅 2025-10-16    👤 surdeus    👁️ 1      

surdeus

I have this situation: Our model includes a struct called Order, that is used very heavily in the codebase.

So we have many, many function signatures of the form order: Order or order: &Order, etc.

The system now requires multiple types of Order. Let's call one "subclass" (!) SpreadOrder. Were this Scala, I'd have trait Order with class SpreadOrder: Order.

Of course, Rust works differently. Options I'm considering:

  • Converting Order to a trait
  • Converting Order to an enum - this hierarchy is essentially a sum ADT

I wanted to avoid large-scale conversion of function signatures but that is probably not possible. I want to implement the best solution, even if the conversion is painful.

Other things to note:

  • Order has many fields and methods. I don't want any solution that involves some kind of wrapper with delegation.
  • I do not need dynamic dispatch

The problem with the enum solution

pub enum Order {
    Single(SingleOrder),
    Spread(SpreadOrder),
}

is that the large number of base Order fields have to be duplicated in Spread (and other variants).

The problem with a trait-based solution is that, since Rust lacks implementation inheritence, the base set of fields/methods would need to be repeated (whether or not we wrap some BaseOrder struct that contains the common fields/methods).

I think there is probably no way to get around some kind of wrapper with delegation. But I would love to get input.

I realize this is a rather open-ended modeling question. Again, just looking for some input.

8 posts - 4 participants

Read full topic

🏷️ Rust_feed