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