rust/conversions.md

32 lines
793 B
Markdown
Raw Normal View History

2015-06-08 09:57:05 -07:00
% Type Conversions
2015-06-10 13:57:00 -07:00
At the end of the day, everything is just a pile of bits somewhere, and type systems
are just there to help us use those bits right. Needing to reinterpret those piles
of bits as different types is a common problem and Rust consequently gives you
several ways to do that.
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 its constituent
parts and then build a new type out of them. e.g.
```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
}
```
But this is, at best, annoying to do. For common conversions, rust provides
more ergonomic alternatives.