diff --git a/src/doc/book/structs.md b/src/doc/book/structs.md index cfd00cf997e0b..5a13746d0a87f 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 diff --git a/src/doc/grammar.md b/src/doc/grammar.md index 690d44cc2cb7b..3dc09d21e7eea 100644 --- a/src/doc/grammar.md +++ b/src/doc/grammar.md @@ -510,8 +510,9 @@ unit_expr : "()" ; ### Structure expressions ```antlr -struct_expr : expr_path '{' ident ':' expr - [ ',' ident ':' expr ] * +field_init : ident | ident ':' expr; +struct_expr : expr_path '{' field_init + [ ',' field_init ] * [ ".." expr ] '}' | expr_path '(' expr [ ',' expr ] * ')' | diff --git a/src/doc/reference.md b/src/doc/reference.md index 4112b328f612e..9e821e53a7115 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -2757,6 +2757,19 @@ 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: + +``` +let a = SomeStruct { field1, field2: expression, field3 }; +let b = SomeStruct { field1: field1, field2: expression, field3: field3 }; +``` + ### Block expressions A _block expression_ is similar to a module in terms of the declarations that