]>
Commit | Line | Data |
---|---|---|
ea8adc8c XL |
1 | # Type aliases |
2 | ||
8faf50e0 XL |
3 | > **<sup>Syntax</sup>**\ |
4 | > _TypeAlias_ :\ | |
5869c6ff | 5 | > `type` [IDENTIFIER] [_GenericParams_]<sup>?</sup> |
136023e0 | 6 | > ( `:` [_TypeParamBounds_] )<sup>?</sup> |
2b03887a | 7 | > [_WhereClause_]<sup>?</sup> ( `=` [_Type_] [_WhereClause_]<sup>?</sup>)<sup>?</sup> `;` |
ff7c6d11 | 8 | |
ea8adc8c XL |
9 | A _type alias_ defines a new name for an existing [type]. Type aliases are |
10 | declared with the keyword `type`. Every value has a single, specific type, but | |
11 | may implement several different traits, or be compatible with several different | |
12 | type constraints. | |
13 | ||
ea8adc8c XL |
14 | For example, the following defines the type `Point` as a synonym for the type |
15 | `(u8, u8)`, the type of pairs of unsigned 8 bit integers: | |
16 | ||
17 | ```rust | |
18 | type Point = (u8, u8); | |
19 | let p: Point = (41, 68); | |
20 | ``` | |
21 | ||
f035d41b | 22 | A type alias to a tuple-struct or unit-struct cannot be used to qualify that type's constructor: |
ea8adc8c | 23 | |
136023e0 | 24 | ```rust,compile_fail |
f035d41b XL |
25 | struct MyStruct(u32); |
26 | ||
27 | use MyStruct as UseAlias; | |
28 | type TypeAlias = MyStruct; | |
29 | ||
30 | let _ = UseAlias(5); // OK | |
31 | let _ = TypeAlias(5); // Doesn't work | |
ea8adc8c | 32 | ``` |
ff7c6d11 | 33 | |
2b03887a FG |
34 | A type alias, when not used as an associated type, must include a [_Type_] and |
35 | may not include [_TypeParamBounds_]. | |
5869c6ff | 36 | |
2b03887a FG |
37 | A type alias, when used as an [associated type] in a [trait], must not include a |
38 | [_Type_] specification but may include [_TypeParamBounds_]. | |
39 | ||
40 | A type alias, when used as an [associated type] in a [trait impl], must include | |
41 | a [_Type_] specification and may not include [_TypeParamBounds_]. | |
42 | ||
43 | Where clauses before the equals sign on a type alias in a [trait impl] (like | |
44 | `type TypeAlias<T> where T: Foo = Bar<T>`) are deprecated. Where clauses after | |
45 | the equals sign (like `type TypeAlias<T> = Bar<T> where T: Foo`) are preferred. | |
136023e0 | 46 | |
416331ca | 47 | [IDENTIFIER]: ../identifiers.md |
5869c6ff | 48 | [_GenericParams_]: generics.md |
136023e0 | 49 | [_TypeParamBounds_]: ../trait-bounds.md |
416331ca XL |
50 | [_WhereClause_]: generics.md#where-clauses |
51 | [_Type_]: ../types.md#type-expressions | |
5869c6ff XL |
52 | [associated type]: associated-items.md#associated-types |
53 | [trait]: traits.md | |
54 | [type]: ../types.md | |
2b03887a | 55 | [trait impl]: implementations.md#trait-implementations |