rust/src/doc/nomicon/conversions.md

35 lines
1015 B
Markdown
Raw Normal View History

2015-06-08 09:57:05 -07:00
% Type Conversions
2015-07-14 09:56:10 -07:00
At the end of the day, everything is just a pile of bits somewhere, and type
2015-07-19 21:43:17 -07:00
systems are just there to help us use those bits right. There are two common
problems with typing bits: needing to reinterpret those exact bits as a
different type, and needing to change the bits to have equivalent meaning for
a different type. Because Rust encourages encoding important properties in the
type system, these problems are incredibly pervasive. As such, Rust
consequently gives you several ways to solve them.
2015-06-10 13:57:00 -07:00
2015-07-30 18:47:02 -07:00
First we'll look at the ways that Safe Rust gives you to reinterpret values.
2015-07-14 09:56:10 -07:00
The most trivial way to do this is to just destructure a value into its
constituent parts and then build a new type out of them. e.g.
2015-06-10 13:57:00 -07:00
```rust
struct Foo {
2015-06-18 21:04:48 -07:00
x: u32,
y: u16,
2015-06-10 13:57:00 -07:00
}
struct Bar {
2015-06-18 21:04:48 -07:00
a: u32,
b: u16,
2015-06-10 13:57:00 -07:00
}
fn reinterpret(foo: Foo) -> Bar {
2015-06-18 21:04:48 -07:00
let Foo { x, y } = foo;
Bar { a: x, b: y }
2015-06-10 13:57:00 -07:00
}
```
2015-07-19 21:43:17 -07:00
But this is, at best, annoying. For common conversions, Rust provides
2015-06-10 13:57:00 -07:00
more ergonomic alternatives.