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

Rust: Difference between pass by reference and by box

Chris Morgan
Jul 08, 2015
<p>When you pass a boxed value, you are moving the value completely. You no longer own it, the thing you passed it to does. It is so for any type that is not <code>Copy</code> (plain old data that can just be <code>memcpy</code>’d, which a heap allocation certainly can’t be). This is how Rust’s ownership model works: each object is owned in exactly one place.</p> <p>If you wish to mutate the <em>contents</em> of the box, you should pass in a <code>&amp;mut int</code> rather than the whole <code>Box&lt;int&gt;</code>.</p> <p>Really, <code>Box&lt;T&gt;</code> is only useful for recursive data structures (so that they can be represented rather than being of infinite size) and for the <em>very</em> occasional performance optimisation on large types (which you shouldn’t try doing without measurements).</p> <p>To get <code>&amp;mut int</code> out of a <code>Box&lt;int&gt;</code>, take a mutable reference to the dereferenced box, i.e. <code>&amp;mut *heap_a</code>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/27305585/Rust:%20Difference%20between%20pass%20by%20reference%20and%20by%20box/27305838">Stack Overflow</a>.</p>
comments powered by Disqus