Transmutes

Get out of our way type system! We’re going to reinterpret these bits or dietrying! Even though this book is all about doing things that are unsafe, Ireally can’t emphasize that you should deeply think about finding Another Waythan the operations covered in this section. This is really, truly, the mosthorribly unsafe thing you can do in Rust. The railguards here are dental floss.

mem::transmute<T, U> takes a value of type T and reinterpretsit to have type U. The only restriction is that the T and U are verifiedto have the same size. The ways to cause Undefined Behavior with this are mindboggling.

  • First and foremost, creating an instance of any type with an invalid stateis going to cause arbitrary chaos that can’t really be predicted.
  • Transmute has an overloaded return type. If you do not specify the return typeit may produce a surprising type to satisfy inference.
  • Making a primitive with an invalid value is UB
  • Transmuting between non-repr(C) types is UB
  • Transmuting an & to &mut is UB
    • Transmuting an & to &mut is always UB
    • No you can’t do it
    • No you’re not special
  • Transmuting to a reference without an explicitly provided lifetimeproduces an unbounded lifetime

mem::transmute_copy<T, U> somehow manages to be even morewildly unsafe than this. It copies size_of<U> bytes out of an &T andinterprets them as a U. The size check that mem::transmute has is gone (asit may be valid to copy out a prefix), though it is Undefined Behavior for Uto be larger than T.

Also of course you can get most of the functionality of these functions usingpointer casts.