× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

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

Chris Morgan
Jul 08, 2015
<p>There are really only a few times you need to use <code>Box</code>:</p> <ul> <li><p>Recursive data structures: not relevant for the outermost element, so no need for <code>Vec&lt;Box&lt;T&gt;&gt;</code>.</p></li> <li><p>Owned trait object, which must be <code>Box&lt;Trait&gt;</code> because the size of the object is dynamic;</p></li> <li><p>Things that are sensitive to particular memory addresses, in order that the contained object will keep the same memory location (practically never the case and definitely not the case in any stable public API; some of the handle stuff to do with <code>std::sync::mpsc::Select</code> is the only case that I am aware of; this unsafety and care required is a part of why <a href="http://doc.rust-lang.org/std/macro.select!.html" rel="nofollow"><code>select!</code></a> exists. This sort of a thing (<code>Handle.add</code>) is unsafe stuff.</p></li> </ul> <p>If none of these situations apply, <em>you should not use <code>Box</code></em>. And <code>Box&lt;Vec&lt;T&gt;&gt;</code> is one such case; the boxing is completely superfluous, adding an additional level of indirection to no benefit whatsoever.</p> <p>So the simple version is:</p> <ul> <li><code>Box&lt;Vec&lt;T&gt;&gt;</code>: never.</li> <li><code>Vec&lt;Box&lt;T&gt;&gt;</code>: only if <code>T</code> is a trait, i.e. you’re working with trait objects.</li> </ul> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29847928/When%20to%20use%20Box&lt;Vec&lt;..&gt;&gt;%20or%20Vec&lt;Box&lt;..&gt;&gt;?/29848802">Stack Overflow</a>.</p>
comments powered by Disqus