File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 2
2
3
3
This appendix documents features that have been added to stable Rust since the
4
4
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
+ ```
You can’t perform that action at this time.
0 commit comments