]> git.proxmox.com Git - rustc.git/blame - src/doc/reference/src/items/type-aliases.md
New upstream version 1.66.0+dfsg1
[rustc.git] / src / doc / reference / src / items / type-aliases.md
CommitLineData
ea8adc8c
XL
1# Type aliases
2
8faf50e0
XL
3> **<sup>Syntax</sup>**\
4> _TypeAlias_ :\
5869c6ff 5> &nbsp;&nbsp; `type` [IDENTIFIER]&nbsp;[_GenericParams_]<sup>?</sup>
136023e0 6> ( `:` [_TypeParamBounds_] )<sup>?</sup>
2b03887a 7> [_WhereClause_]<sup>?</sup> ( `=` [_Type_] [_WhereClause_]<sup>?</sup>)<sup>?</sup> `;`
ff7c6d11 8
ea8adc8c
XL
9A _type alias_ defines a new name for an existing [type]. Type aliases are
10declared with the keyword `type`. Every value has a single, specific type, but
11may implement several different traits, or be compatible with several different
12type constraints.
13
ea8adc8c
XL
14For 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
18type Point = (u8, u8);
19let p: Point = (41, 68);
20```
21
f035d41b 22A 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
25struct MyStruct(u32);
26
27use MyStruct as UseAlias;
28type TypeAlias = MyStruct;
29
30let _ = UseAlias(5); // OK
31let _ = TypeAlias(5); // Doesn't work
ea8adc8c 32```
ff7c6d11 33
2b03887a
FG
34A type alias, when not used as an associated type, must include a [_Type_] and
35may not include [_TypeParamBounds_].
5869c6ff 36
2b03887a
FG
37A type alias, when used as an [associated type] in a [trait], must not include a
38[_Type_] specification but may include [_TypeParamBounds_].
39
40A type alias, when used as an [associated type] in a [trait impl], must include
41a [_Type_] specification and may not include [_TypeParamBounds_].
42
43Where 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
45the 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