]>
Commit | Line | Data |
---|---|---|
9346a6ac AL |
1 | % `type` Aliases |
2 | ||
bd371182 AL |
3 | The `type` keyword lets you declare an alias of another type: |
4 | ||
5 | ```rust | |
6 | type Name = String; | |
7 | ``` | |
8 | ||
9 | You can then use this type as if it were a real type: | |
10 | ||
11 | ```rust | |
12 | type Name = String; | |
13 | ||
14 | let x: Name = "Hello".to_string(); | |
15 | ``` | |
16 | ||
17 | Note, however, that this is an _alias_, not a new type entirely. In other | |
18 | words, because Rust is strongly typed, you’d expect a comparison between two | |
19 | different types to fail: | |
20 | ||
21 | ```rust,ignore | |
22 | let x: i32 = 5; | |
23 | let y: i64 = 5; | |
24 | ||
25 | if x == y { | |
26 | // ... | |
27 | } | |
28 | ``` | |
29 | ||
30 | this gives | |
31 | ||
32 | ```text | |
33 | error: mismatched types: | |
34 | expected `i32`, | |
35 | found `i64` | |
36 | (expected i32, | |
37 | found i64) [E0308] | |
38 | if x == y { | |
39 | ^ | |
40 | ``` | |
41 | ||
42 | But, if we had an alias: | |
43 | ||
44 | ```rust | |
45 | type Num = i32; | |
46 | ||
47 | let x: i32 = 5; | |
48 | let y: Num = 5; | |
49 | ||
50 | if x == y { | |
51 | // ... | |
52 | } | |
53 | ``` | |
54 | ||
55 | This compiles without error. Values of a `Num` type are the same as a value of | |
56 | type `i32`, in every way. | |
57 | ||
58 | You can also use type aliases with generics: | |
59 | ||
60 | ```rust | |
61 | use std::result; | |
62 | ||
63 | enum ConcreteError { | |
64 | Foo, | |
65 | Bar, | |
66 | } | |
67 | ||
68 | type Result<T> = result::Result<T, ConcreteError>; | |
69 | ``` | |
70 | ||
71 | This creates a specialized version of the `Result` type, which always has a | |
72 | `ConcreteError` for the `E` part of `Result<T, E>`. This is commonly used | |
73 | in the standard library to create custom errors for each subsection. For | |
74 | example, [io::Result][ioresult]. | |
75 | ||
76 | [ioresult]: ../std/io/type.Result.html |