]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/items/structs.md
New upstream version 1.26.0+dfsg1
[rustc.git] / src / doc / reference / src / items / structs.md
1 # Structs
2
3 > **<sup>Syntax</sup>**
4 > _Struct_ :
5 > &nbsp;&nbsp; &nbsp;&nbsp; _StructStruct_
6 > &nbsp;&nbsp; | _TupleStruct_
7 >
8 > _StructStruct_ :
9 > &nbsp;&nbsp; `struct`
10 > [IDENTIFIER]&nbsp;
11 > [_Generics_]<sup>?</sup>
12 > [_WhereClause_]<sup>?</sup>
13 > ( `{` _StructFields_<sup>?</sup> `}` | `;` )
14 >
15 > _TupleStruct_ :
16 > &nbsp;&nbsp; `struct`
17 > [IDENTIFIER]&nbsp;
18 > [_Generics_]<sup>?</sup>
19 > `(` _TupleFields_<sup>?</sup> `)`
20 > [_WhereClause_]<sup>?</sup>
21 > `;`
22 >
23 > _StructFields_ :
24 > &nbsp;&nbsp; _StructField_ (`,` _StructField_)<sup>\*</sup> `,`<sup>?</sup>
25 >
26 > _StructField_ :
27 > &nbsp;&nbsp; [_OuterAttribute_]<sup>\*</sup>
28 > &nbsp;&nbsp; [_Visibility_]
29 > &nbsp;&nbsp; [IDENTIFIER] `:` [_Type_]
30 >
31 > _TupleFields_ :
32 > &nbsp;&nbsp; _TupleField_ (`,` _TupleField_)<sup>\*</sup> `,`<sup>?</sup>
33 >
34 > _TupleField_ :
35 > &nbsp;&nbsp; [_OuterAttribute_]<sup>\*</sup>
36 > &nbsp;&nbsp; [_Visibility_]
37 > &nbsp;&nbsp; [_Type_]
38
39 A _struct_ is a nominal [struct type] defined with the keyword `struct`.
40
41 An example of a `struct` item and its use:
42
43 ```rust
44 struct Point {x: i32, y: i32}
45 let p = Point {x: 10, y: 11};
46 let px: i32 = p.x;
47 ```
48
49 A _tuple struct_ is a nominal [tuple type], also defined with the keyword
50 `struct`. For example:
51
52 [struct type]: types.html#struct-types
53 [tuple type]: types.html#tuple-types
54
55 ```rust
56 struct Point(i32, i32);
57 let p = Point(10, 11);
58 let px: i32 = match p { Point(x, _) => x };
59 ```
60
61 A _unit-like struct_ is a struct without any fields, defined by leaving off the
62 list of fields entirely. Such a struct implicitly defines a constant of its
63 type with the same name. For example:
64
65 ```rust
66 struct Cookie;
67 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
68 ```
69
70 is equivalent to
71
72 ```rust
73 struct Cookie {}
74 const Cookie: Cookie = Cookie {};
75 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
76 ```
77
78 The precise memory layout of a struct is not specified. One can specify a
79 particular layout using the [`repr` attribute].
80
81 [`repr` attribute]: attributes.html#ffi-attributes
82
83 [_OuterAttribute_]: attributes.html
84 [IDENTIFIER]: identifiers.html
85 [_Generics_]: items.html#type-parameters
86 [_WhereClause_]: items.html#type-parameters
87 [_Visibility_]: visibility-and-privacy.html
88 [_Type_]: types.html