blob: c819002c289de03d6e88faa699d52f26303dab77 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
# New Type Idiom
The `newtype` idiom gives compile time guarantees that the right type of value is supplied
to a program.
For example, an age verification function that checks age in years, *must* be given
a value of type `Years`.
```rust, editable
struct Years(i64);
struct Days(i64);
impl Years {
pub fn to_days(&self) -> Days {
Days(self.0 * 365)
}
}
impl Days {
/// truncates partial years
pub fn to_years(&self) -> Years {
Years(self.0 / 365)
}
}
fn old_enough(age: &Years) -> bool {
age.0 >= 18
}
fn main() {
let age = Years(5);
let age_days = age.to_days();
println!("Old enough {}", old_enough(&age));
println!("Old enough {}", old_enough(&age_days.to_years()));
// println!("Old enough {}", old_enough(&age_days));
}
```
Uncomment the last print statement to observe that the type supplied must be `Years`.
To obtain the `newtype`'s value as the base type, you may use the tuple or destructuring syntax like so:
```rust, editable
struct Years(i64);
fn main() {
let years = Years(42);
let years_as_primitive_1: i64 = years.0; // Tuple
let Years(years_as_primitive_2) = years; // Destructuring
}
```
### See also:
[`structs`][struct]
[struct]: ../custom_types/structs.md
|