title: Rust: macro for the length of an array
body: <p>I've got a file containing raw binary data, that I would like to load to an array of 4 byte long <code>u32</code> words.</p>
  
  <p>It's possible to do by including the contents of the file at compile time:</p>
  
  <pre class="lang-rust prettyprint-override"><code>let bytes = include_bytes!("audio.raw");
  </code></pre>
  
  <p>Then, I can convert it to an array of <code>u32</code> words using <code>transmute</code>. The length of the new array should be obviously 1/4 of the original byte array.</p>
  
  <pre class="lang-rust prettyprint-override"><code>let audio = unsafe { std::mem::transmute::&lt;[u8; 63504], [u32; 15876]&gt;(*bytes) };
  // works
  </code></pre>
  
  <p>As you can see above, I had to hardcode the lengthes of the input and output arrays. However when trying to avoid hardcoding these numbers, it doesn't work:</p>
  
  <pre class="lang-rust prettyprint-override"><code>let audio = unsafe { std::mem::transmute::&lt;[u8; bytes.len()], [u32; bytes.len()/4]&gt;(*bytes) };
  // error: non-constant value
  </code></pre>
  
  <p>It seems that <code>.len()</code> is called at runtime, and since dynamic arrays cannot be allocated in Rust, it yields an error. However in theory, there should be a way to calculate the necessary length at compilation stage, as the length of the <code>bytes</code> array is fixed. So my question is: is there a macro that gives back the length of a static array?</p>
  
  <p>(I'm perfectly aware that dynamic allocation is possible with vectors, my question is explicitly about fixed-sized arrays.)</p>
  
  <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=cef399e1a97f8ec15eb3533bf64253ef" rel="nofollow noreferrer">Sample code</a> (<code>include_bytes</code> replaced with hard-coded array):</p>
  
  <pre class="lang-rust prettyprint-override"><code>fn main() {
      // let bytes = include_bytes!("audio.raw");
      let bytes = [1, 0, 0, 0, 2, 0, 0, 0];
  
      // works:
      let audio = unsafe { std::mem::transmute::&lt;[u8; 8], [u32; 2]&gt;(bytes) };
  
      // error:
      let audio = unsafe { std::mem::transmute::&lt;[u8; bytes.len()], [u32; bytes.len() / 4]&gt;(bytes) };
  
      println!("{}", audio[1]);
  }
  </code></pre>