title: Transmuting u8 buffer to struct in Rust
body: <p>I have a byte buffer of unknown size, and I want to create a local struct variable pointing to the memory of the beginning of the buffer. Following what I'd do in C, I tried a lot of different things in Rust and kept getting errors. This is my latest attempt:</p>
  
  <pre><code>use std::mem::{size_of, transmute};
  
  #[repr(C, packed)]
  struct MyStruct {
      foo: u16,
      bar: u8,
  }
  
  fn main() {
      let v: Vec&lt;u8&gt; = vec![1, 2, 3];
      let buffer = v.as_slice();
      let s: MyStruct = unsafe { transmute(buffer[..size_of::&lt;MyStruct&gt;()]) };
  }
  </code></pre>
  
  <p>I get an error:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
     --&gt; src/main.rs:12:42
      |
  12  |     let s: MyStruct = unsafe { transmute(buffer[..size_of::&lt;MyStruct&gt;()]) };
      |                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
      |
      = help: the trait `std::marker::Sized` is not implemented for `[u8]`
      = note: to learn more, visit &lt;https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait&gt;
  </code></pre>