]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/expressions/struct-expr.md
8caeff200a4b466ac59cd451dde18feee40e563c
[rustc.git] / src / doc / reference / src / expressions / struct-expr.md
1 # Struct expressions
2
3 > **<sup>Syntax</sup>**\
4 > _StructExpression_ :\
5 > &nbsp;&nbsp; &nbsp;&nbsp; _StructExprStruct_\
6 > &nbsp;&nbsp; | _StructExprTuple_\
7 > &nbsp;&nbsp; | _StructExprUnit_
8 >
9 > _StructExprStruct_ :\
10 > &nbsp;&nbsp; [_PathInExpression_] `{` (_StructExprFields_ | _StructBase_)<sup>?</sup> `}`
11 >
12 > _StructExprFields_ :\
13 > &nbsp;&nbsp; _StructExprField_ (`,` _StructExprField_)<sup>\*</sup> (`,` _StructBase_ | `,`<sup>?</sup>)
14 >
15 > _StructExprField_ :\
16 > &nbsp;&nbsp; [_OuterAttribute_] <sup>\*</sup>\
17 > &nbsp;&nbsp; (\
18 > &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; [IDENTIFIER]\
19 > &nbsp;&nbsp; &nbsp;&nbsp; | ([IDENTIFIER] | [TUPLE_INDEX]) `:` [_Expression_]\
20 > &nbsp;&nbsp; )
21 >
22 > _StructBase_ :\
23 > &nbsp;&nbsp; `..` [_Expression_]
24 >
25 > _StructExprTuple_ :\
26 > &nbsp;&nbsp; [_PathInExpression_] `(`\
27 > &nbsp;&nbsp; &nbsp;&nbsp; ( [_Expression_] (`,` [_Expression_])<sup>\*</sup> `,`<sup>?</sup> )<sup>?</sup>\
28 > &nbsp;&nbsp; `)`
29 >
30 > _StructExprUnit_ : [_PathInExpression_]
31
32 A *struct expression* creates a struct, enum, or union value.
33 It consists of a path to a [struct], [enum variant], or [union] item followed by the values for the fields of the item.
34 There are three forms of struct expressions: struct, tuple, and unit.
35
36 The following are examples of struct expressions:
37
38 ```rust
39 # struct Point { x: f64, y: f64 }
40 # struct NothingInMe { }
41 # struct TuplePoint(f64, f64);
42 # mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } }
43 # struct Cookie; fn some_fn<T>(t: T) {}
44 Point {x: 10.0, y: 20.0};
45 NothingInMe {};
46 TuplePoint(10.0, 20.0);
47 TuplePoint { 0: 10.0, 1: 20.0 }; // Results in the same value as the above line
48 let u = game::User {name: "Joe", age: 35, score: 100_000};
49 some_fn::<Cookie>(Cookie);
50 ```
51
52 ## Field struct expression
53
54 A struct expression with fields enclosed in curly braces allows you to specify the value for each individual field in any order.
55 The field name is separated from its value with a colon.
56
57 A value of a [union] type can only be created using this syntax, and it must specify exactly one field.
58
59 ## Functional update syntax
60
61 A struct expression that constructs a value of a struct type can terminate with the syntax `..` followed by an expression to denote a functional update.
62 The expression following `..` (the base) must have the same struct type as the new struct type being formed.
63
64 The entire expression uses the given values for the fields that were specified and moves or copies the remaining fields from the base expression.
65 As with all struct expressions, all of the fields of the struct must be [visible], even those not explicitly named.
66
67 ```rust
68 # struct Point3d { x: i32, y: i32, z: i32 }
69 let mut base = Point3d {x: 1, y: 2, z: 3};
70 let y_ref = &mut base.y;
71 Point3d {y: 0, z: 10, .. base}; // OK, only base.x is accessed
72 drop(y_ref);
73 ```
74
75 Struct expressions with curly braces can't be used directly in a [loop] or [if] expression's head, or in the [scrutinee] of an [if let] or [match] expression.
76 However, struct expressions can be in used in these situations if they are within another expression, for example inside [parentheses].
77
78 The field names can be decimal integer values to specify indices for constructing tuple structs.
79 This can be used with base structs to fill out the remaining indices not specified:
80
81 ```rust
82 struct Color(u8, u8, u8);
83 let c1 = Color(0, 0, 0); // Typical way of creating a tuple struct.
84 let c2 = Color{0: 255, 1: 127, 2: 0}; // Specifying fields by index.
85 let c3 = Color{1: 0, ..c2}; // Fill out all other fields using a base struct.
86 ```
87
88 ### Struct field init shorthand
89
90 When initializing a data structure (struct, enum, union) with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`.
91 This allows a compact syntax with less duplication.
92 For example:
93
94 ```rust
95 # struct Point3d { x: i32, y: i32, z: i32 }
96 # let x = 0;
97 # let y_value = 0;
98 # let z = 0;
99 Point3d { x: x, y: y_value, z: z };
100 Point3d { x, y: y_value, z };
101 ```
102
103 ## Tuple struct expression
104
105 A struct expression with fields enclosed in parentheses constructs a tuple struct.
106 Though it is listed here as a specific expression for completeness, it is equivalent to a [call expression] to the tuple struct's constructor. For example:
107
108 ```rust
109 struct Position(i32, i32, i32);
110 Position(0, 0, 0); // Typical way of creating a tuple struct.
111 let c = Position; // `c` is a function that takes 3 arguments.
112 let pos = c(8, 6, 7); // Creates a `Position` value.
113 ```
114
115 ## Unit struct expression
116
117 A unit struct expression is just the path to a unit struct item.
118 This refers to the unit struct's implicit constant of its value.
119 The unit struct value can also be constructed with a fieldless struct expression. For example:
120
121 ```rust
122 struct Gamma;
123 let a = Gamma; // Gamma unit value.
124 let b = Gamma{}; // Exact same value as `a`.
125 ```
126
127 [_OuterAttribute_]: ../attributes.md
128 [IDENTIFIER]: ../identifiers.md
129 [TUPLE_INDEX]: ../tokens.md#tuple-index
130 [_Expression_]: ../expressions.md
131 [_PathInExpression_]: ../paths.md#paths-in-expressions
132 [call expression]: call-expr.md
133 [enum variant]: ../items/enumerations.md
134 [if let]: if-expr.md#if-let-expressions
135 [if]: if-expr.md#if-expressions
136 [loop]: loop-expr.md
137 [match]: match-expr.md
138 [parentheses]: grouped-expr.md
139 [struct]: ../items/structs.md
140 [union]: ../items/unions.md
141 [visible]: ../visibility-and-privacy.md
142 [scrutinee]: ../glossary.md#scrutinee