Field init shorthand

Minimum Rust version: 1.17

In older Rust, when initializing a struct, you must always give the full set of key: value pairsfor its fields:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. struct Point {
  4. x: i32,
  5. y: i32,
  6. }
  7. let a = 5;
  8. let b = 6;
  9. let p = Point {
  10. x: a,
  11. y: b,
  12. };
  13. }

However, often these variables would have the same names as the fields. So you'd end upwith code that looks like this:

  1. let p = Point {
  2. x: x,
  3. y: y,
  4. };

Now, if the variable is of the same name, you don't have to write out both, just write out the key:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. struct Point {
  4. x: i32,
  5. y: i32,
  6. }
  7. let x = 5;
  8. let y = 6;
  9. // new
  10. let p = Point {
  11. x,
  12. y,
  13. };
  14. }