When to use Box <Vec <.. >> or Vec <Box <.. >>?

When would it be appropriate to create a data structure nested in Box

and a Vec

(or vice versa)?

It looks like in most situations where you want to store multiple chunks of a fixed size on the heap Box

is overkill, since its role (?) Is to dock-allocate one value, and the normal Vec

one is already the heap allocating that storage.

Context: I am still embracing the roles of different types of rust for building data structures.


source to share

1 answer

There are only a few times when you need to use Box


  • Recursive data structures: does not refer to the outermost element, so there is no need for Vec<Box<T>>


  • Own object object, which should be Box<Trait>

    because the size of the object is dynamic;

  • Things that are sensitive to specific memory addresses so that the contained objects keep the same location in memory (almost never happened and definitely not in any stable public API, some of the c descriptor elements std::sync::mpsc::Select

    is the only case I know of, this insecurity and caring is part of why there is a select!

    kind of thing ( Handle.add

    ) is unsafe stuff.

If none of these situations apply, you should not use Box

. And Box<Vec<T>>

- one of such cases; boxing is completely redundant, adding an extra layer of indirection without any benefit.

So the simple version is:

  • Box<Vec<T>>

    : never.
  • Vec<Box<T>>

    : only if it T

    is a feature, i.e. you are working with feature objects.


All Articles