Enum or Trait trade-offs

I was just thinking about whether I should use an enum or a set of structs which implement a trait.

I googled and this article came up:

What it doesn't mention ( perhaps because it's not that important ) is that an enum will ( I think! ) take up the space of it's largest variant. So if some variants have a lot of fields, but others have few, there could be a cost in terms of increased memory usage. Have I got this right?

Yes, although note that large variants can be boxed to avoid the issue.

1 Like

Related to that is that trait objects are unsized and thus must be stored in a heap container (Box, Rc, etc) or coerced from a reference. Enums, on the other hand are usually (always?) sized, so can be stored directly inside structs, used as local variables, and have self-consuming methods.

1 Like

Another trade-off not mentioned yet is that in many cases an enum is more cumbersome to work with. If you want to call a method on whatever value is inside the enum, you'll need to match on the value and repeat the function call on each match arm, whereas with a trait object you can just call it. In addition to the existing enum_dispatch, I also wrote a similar macro to alleviate the ergonomics issue: impl-enum.

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.