Is there any downside of transmuting a struct?

I have a scenario where I want to store the state of the user at the client as encrypted byte slice and I am planning to just transmute the struct into a byte slice and encrypting it and then the same way converting it back to the struct when I need it.
What are the potential issues I might encounter with this approach?
I looked into the bincode crate but it seems it is serializing the field names and everything which is not really necessary in my use-case.
What I want is similar to protobuf but instead of a schema file I will be using a struct directly and only I will be reading that value again.

  • If your data structure has any sort of pointer in it (e.g. a Vec), then transmuting bytes will circumvent the lifetime system by copying raw pointers.
  • If you communicate the transmuted bytes (encrypted or not), the endianness may differ between the two endpoint machines, changing the values of any integers in the struct.
  • Rust data structure layout is unstable and is allowed to change between different compiler versions, different architectures, or theoretically even between different builds of the exact same program with the exact same toolchain! So if you want to write the bytes to a file and read them back later, you must make sure the layout is well-specified using #[repr(C)].
  • Even #[repr(C)] data structures may contain padding, and copying these padding bytes as u8 is currently understood to be UB. To work around this, you must design your structure to have no padding. (actually, can that even be done in a cross-platform manner? I don't know! Maybe you need #[repr(packed)]!)

Also relavant to this discussion: The abomonation crate mentioned in the linked thread exists exactly for this purpose, and if that thread is any indication, they're having a hard time removing all of the UB!


If you do that you will read uninitialized memory from padding bytes and induce UB. I am pretty sure that bincode doesn't store field names so it should be exactly what you need.


Thanks everyone i think i will go with bincode then