Skip to content

Commit 071f6de

Browse files
authored
Rollup merge of rust-lang#39459 - phungleson:fix-short-hand-struct-doc, r=steveklabnik
Fix short hand struct doc Don't want to discredit @HnGiang effort on this issue. I just want to lend a hand to fix this issue rust-lang#38830, it is a very nice feature and is seemingly completed. Fixes rust-lang#39096 r? @steveklabnik
2 parents e49ec1c + 4ddb56b commit 071f6de

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/doc/book/structs.md

+24
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,30 @@ fn main() {
117117
}
118118
```
119119

120+
Initialization of a data structure (struct, enum, union) can be simplified if
121+
fields of the data structure are initialized with variables which has same
122+
names as the fields.
123+
124+
```
125+
#![feature(field_init_shorthand)]
126+
127+
#[derive(Debug)]
128+
struct Person<'a> {
129+
name: &'a str,
130+
age: u8
131+
}
132+
133+
fn main() {
134+
// Create struct with field init shorthand
135+
let name = "Peter";
136+
let age = 27;
137+
let peter = Person { name, age };
138+
139+
// Print debug struct
140+
println!("{:?}", peter);
141+
}
142+
```
143+
120144
# Update syntax
121145

122146
A `struct` can include `..` to indicate that you want to use a copy of some

src/doc/reference.md

+22
Original file line numberDiff line numberDiff line change
@@ -2765,6 +2765,28 @@ let base = Point3d {x: 1, y: 2, z: 3};
27652765
Point3d {y: 0, z: 10, .. base};
27662766
```
27672767

2768+
#### Struct field init shorthand
2769+
2770+
When initializing a data structure (struct, enum, union) with named fields,
2771+
allow writing `fieldname` as a shorthand for `fieldname: fieldname`. This
2772+
allows a compact syntax for initialization, with less duplication.
2773+
2774+
In the initializer for a `struct` with named fields, a `union` with named
2775+
fields, or an enum variant with named fields, accept an identifier `field` as a
2776+
shorthand for `field: field`.
2777+
2778+
Example:
2779+
2780+
```
2781+
# #![feature(field_init_shorthand)]
2782+
# struct Point3d { x: i32, y: i32, z: i32 }
2783+
# let x = 0;
2784+
# let y_value = 0;
2785+
# let z = 0;
2786+
Point3d { x: x, y: y_value, z: z };
2787+
Point3d { x, y: y_value, z };
2788+
```
2789+
27682790
### Block expressions
27692791

27702792
A _block expression_ is similar to a module in terms of the declarations that

0 commit comments

Comments
 (0)