1 Heterogeneous collections
Vectornaut edited this page 2026-01-15 22:30:14 +00:00

The question came up in a recent meeting about how to handle a collection of different sorts of Elements in an Assembly, or Regulators, etc. A bit of web searching reveals two main ways to do this in Rust.

Enums

More appropriate when the list of alternatives is relatively small, similar, and not too likely to need lots of extension.

Trait objects

If you define a trait, and have a number of types that implement that trait (possibly completely disparate in a concrete sense), then you can treat pointers/references to entities that implement that trait as a uniform type and put them in collections. Rust will autogenerate a vtable of functions to call the appropriate implementation on each at runtime when you call the trait methods through such a pointer/reference. In other words, we can define the interface(s) that Elements and Regulators support, and then have as many different implementations of those as we like, and still use them interchangeably through the corresponding trait objects. This blog entry is a decent reference, albeit quite old now. Not sure if recent language developments have created better takes on some of the things we might want to do along these lines.