diff options
| author | Giang Nguyen <nguyengiangdev@gmail.com> | 2017-01-16 16:58:07 +0700 |
|---|---|---|
| committer | Son <leson.phung@gmail.com> | 2017-02-02 22:19:41 +1100 |
| commit | a7b65f15781e479d6d0cd98f0865cc3ec0dc03ac (patch) | |
| tree | 06fbe1bda97c711b05cfb5ab795593a90204a69d | |
| parent | 3388855443ccfdce427dbbbf8c3d7c3c78bd7b81 (diff) | |
Add doc field init shorthand
| -rw-r--r-- | src/doc/book/structs.md | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/src/doc/book/structs.md b/src/doc/book/structs.md index cfd00cf997e..5a13746d0a8 100644 --- a/src/doc/book/structs.md +++ b/src/doc/book/structs.md @@ -117,6 +117,28 @@ fn main() { } ``` +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: + +``` +#![feature(field_init_shorthand)] + +#[derive(Debug)] +struct Person<'a> { + name: &'a str, + age: u8 +} + +fn main() { + // Create struct with field init shorthand + let name = "Peter"; + let age = 27; + let peter = Person { name, age }; + + // Print debug struct + println!("{:?}", peter); +} +``` + # Update syntax A `struct` can include `..` to indicate that you want to use a copy of some |
