Skip to content

Commit e90abc5

Browse files
committed
Document field init shorthand
From RFC 1682. This is an updated version of #405. cc rust-lang/rust#39096
1 parent 888ea44 commit e90abc5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

second-edition/src/appendix-07-newest-features.md

+31
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,34 @@
22

33
This appendix documents features that have been added to stable Rust since the
44
main part of the book was completed.
5+
6+
7+
## Field init shorthand
8+
9+
We can initialize a data structure (struct, enum, union) with named
10+
fields, by writing `fieldname` as a shorthand for `fieldname: fieldname`.
11+
This allows a compact syntax for initialization, with less duplication:
12+
13+
```rust
14+
#[derive(Debug)]
15+
struct Person {
16+
name: String,
17+
age: u8,
18+
}
19+
20+
fn main() {
21+
let name = String::from("Peter");
22+
let age = 27;
23+
24+
// Using full syntax:
25+
let peter = Person { name: name, age: age };
26+
27+
let name = String::from("Portia");
28+
let age = 27;
29+
30+
// Using field init shorthand:
31+
let portia = Person { name, age };
32+
33+
println!("{:?}", portia);
34+
}
35+
```

0 commit comments

Comments
 (0)