]> git.lizzy.rs Git - rust.git/blob - src/doc/tarpl/conversions.md
2309c45c6a84fee8e28e8ae12d0ba5e7a62f28b4
[rust.git] / src / doc / tarpl / conversions.md
1 % Type Conversions
2
3 At the end of the day, everything is just a pile of bits somewhere, and type
4 systems are just there to help us use those bits right. There are two common
5 problems with typing bits: needing to reinterpret those exact bits as a
6 different type, and needing to change the bits to have equivalent meaning for
7 a different type. Because Rust encourages encoding important properties in the
8 type system, these problems are incredibly pervasive. As such, Rust
9 consequently gives you several ways to solve them.
10
11 First we'll look at the ways that *Safe Rust* gives you to reinterpret values.
12 The most trivial way to do this is to just destructure a value into its
13 constituent parts and then build a new type out of them. e.g.
14
15 ```rust
16 struct Foo {
17     x: u32,
18     y: u16,
19 }
20
21 struct Bar {
22     a: u32,
23     b: u16,
24 }
25
26 fn reinterpret(foo: Foo) -> Bar {
27     let Foo { x, y } = foo;
28     Bar { a: x, b: y }
29 }
30 ```
31
32 But this is, at best, annoying. For common conversions, Rust provides
33 more ergonomic alternatives.
34