There's another strategy that has good storage efficiency and keeps the ability to iterate over elements. vec #1 is a list of tags, vec #2 keeps the byte offset of each element, and vec #3 (not really a vec) is the packed variant data pointed to by vec #2. This:
- is half the number of vecs of the author's final solution (6 vs 3)
- wastes no bytes for padding (unless needed for alignment)
- lets you iterate in a cache-friendly way since the data is laid out in order in memory regardless of type
- even lets you access items by index in O(1)
Generally it has the same performance characteristics as a Vec<T>, but for heterogeneous data.