Skip to content

Commit a7b65f1

Browse files
Giang Nguyenphungleson
Giang Nguyen
authored andcommitted
Add doc field init shorthand
1 parent 3388855 commit a7b65f1

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/doc/book/structs.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,28 @@ fn main() {
117117
}
118118
```
119119

120+
We can initializing a data structure (struct, enum, union) with named fields, by writing `fieldname` as a shorthand for `fieldname: fieldname`. This allows a compact syntax for initialization, with less duplication:
121+
122+
```
123+
#![feature(field_init_shorthand)]
124+
125+
#[derive(Debug)]
126+
struct Person<'a> {
127+
name: &'a str,
128+
age: u8
129+
}
130+
131+
fn main() {
132+
// Create struct with field init shorthand
133+
let name = "Peter";
134+
let age = 27;
135+
let peter = Person { name, age };
136+
137+
// Print debug struct
138+
println!("{:?}", peter);
139+
}
140+
```
141+
120142
# Update syntax
121143

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

0 commit comments

Comments
 (0)