about summary refs log tree commit diff
diff options
context:
space:
mode:
authorCorey Farwell <coreyf@rwell.org>2017-02-07 22:54:26 -0500
committerGitHub <noreply@github.com>2017-02-07 22:54:26 -0500
commitd1f8c448ff9c7b72aba229d729e3309dbfea6dd4 (patch)
treebe70806c5b791ba27fbb7a42c426b65ac0d924e5
parent6fb57bf13fcc316ce622af70d3922ae5d811928d (diff)
parent4ddb56bf4dfdc607ae0bd2207da189c4c4d4c14a (diff)
downloadrust-d1f8c448ff9c7b72aba229d729e3309dbfea6dd4.tar.gz
rust-d1f8c448ff9c7b72aba229d729e3309dbfea6dd4.zip
Rollup merge of #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 #38830, it is a very nice feature and is seemingly completed.

Fixes #39096

r? @steveklabnik
-rw-r--r--src/doc/book/structs.md24
-rw-r--r--src/doc/reference.md22
2 files changed, 46 insertions, 0 deletions
diff --git a/src/doc/book/structs.md b/src/doc/book/structs.md
index cfd00cf997e..dcf74cbb0a7 100644
--- a/src/doc/book/structs.md
+++ b/src/doc/book/structs.md
@@ -117,6 +117,30 @@ fn main() {
 }
 ```
 
+Initialization of a data structure (struct, enum, union) can be simplified if
+fields of the data structure are initialized with variables which has same
+names as the fields.
+
+```
+#![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
diff --git a/src/doc/reference.md b/src/doc/reference.md
index 97ff1c7598f..f9013490418 100644
--- a/src/doc/reference.md
+++ b/src/doc/reference.md
@@ -2765,6 +2765,28 @@ let base = Point3d {x: 1, y: 2, z: 3};
 Point3d {y: 0, z: 10, .. base};
 ```
 
+#### Struct field init shorthand
+
+When initializing a data structure (struct, enum, union) with named fields,
+allow writing `fieldname` as a shorthand for `fieldname: fieldname`. This
+allows a compact syntax for initialization, with less duplication.
+
+In the initializer for a `struct` with named fields, a `union` with named
+fields, or an enum variant with named fields, accept an identifier `field` as a
+shorthand for `field: field`.
+
+Example:
+
+```
+# #![feature(field_init_shorthand)]
+# struct Point3d { x: i32, y: i32, z: i32 }
+# let x = 0;
+# let y_value = 0;
+# let z = 0;
+Point3d { x: x, y: y_value, z: z };
+Point3d { x, y: y_value, z };
+```
+
 ### Block expressions
 
 A _block expression_ is similar to a module in terms of the declarations that