Type Conversions

At the end of the day, everything is just a pile of bits somewhere, and typesystems are just there to help us use those bits right. There are two commonproblems with typing bits: needing to reinterpret those exact bits as adifferent type, and needing to change the bits to have equivalent meaning fora different type. Because Rust encourages encoding important properties in thetype system, these problems are incredibly pervasive. As such, Rustconsequently gives you several ways to solve them.

First we’ll look at the ways that Safe Rust gives you to reinterpret values.The most trivial way to do this is to just destructure a value into itsconstituent parts and then build a new type out of them. e.g.

  1. struct Foo {
  2. x: u32,
  3. y: u16,
  4. }
  5. struct Bar {
  6. a: u32,
  7. b: u16,
  8. }
  9. fn reinterpret(foo: Foo) -> Bar {
  10. let Foo { x, y } = foo;
  11. Bar { a: x, b: y }
  12. }

But this is, at best, annoying. For common conversions, Rust providesmore ergonomic alternatives.