mirror of https://github.com/rust-lang/nomicon
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
1015 B
35 lines
1015 B
8 years ago
|
# Type Conversions
|
||
10 years ago
|
|
||
10 years ago
|
At the end of the day, everything is just a pile of bits somewhere, and type
|
||
10 years ago
|
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.
|
||
10 years ago
|
|
||
9 years ago
|
First we'll look at the ways that Safe Rust gives you to reinterpret values.
|
||
10 years ago
|
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.
|
||
10 years ago
|
|
||
|
```rust
|
||
|
struct Foo {
|
||
10 years ago
|
x: u32,
|
||
|
y: u16,
|
||
10 years ago
|
}
|
||
|
|
||
|
struct Bar {
|
||
10 years ago
|
a: u32,
|
||
|
b: u16,
|
||
10 years ago
|
}
|
||
|
|
||
|
fn reinterpret(foo: Foo) -> Bar {
|
||
10 years ago
|
let Foo { x, y } = foo;
|
||
|
Bar { a: x, b: y }
|
||
10 years ago
|
}
|
||
|
```
|
||
|
|
||
10 years ago
|
But this is, at best, annoying. For common conversions, Rust provides
|
||
10 years ago
|
more ergonomic alternatives.
|
||
|
|