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

Does Rust guarantee that elements of a Vec smaller than a word size will be tightly packed?

Chris Morgan
Jul 15, 2015
<p><strong>Yes.</strong></p> <p>The representation of the contents of a vector is the same as that of a slice, which is the same as that of a fixed-size array. Thus you may compare <code>std::mem::size_of::&lt;[u16, 1]&gt;()</code> and <code>std::mem::size_of::&lt;[u16, 10]&gt;()</code> and see that they always differ by a factor of ten. (<a href="http://is.gd/9rw3rC" rel="nofollow">Citation: this code</a>.)</p> <p>Rust uses byte indexing, so <code>u8</code> takes one byte, <code>u16</code> takes two bytes, <code>u32</code> takes four bytes and <code>u64</code> takes eight bytes. <code>bool</code> also takes one byte; there are seven wasted bits per byte (hence types like the currently unstable <a href="http://doc.rust-lang.org/std/collections/struct.BitVec.html" rel="nofollow"><code>BitVec</code></a>).</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31237408/Does%20Rust%20guarantee%20that%20elements%20of%20a%20Vec%20smaller%20than%20a%20word%20size%20will%20be%20tightly%20packed?/31237579">Stack Overflow</a>.</p>
comments powered by Disqus