Struct initializer ..x syntax should work for other structs with structurally equal subset of fields

6b276d5
Opened by Boscop at 2023-02-26 22:56:43

This should be allowed:

struct X { a: u8, b: u16, c: u32, d: i8 } 
struct Y { a: u8, b: u16, c: u32, d: i8 } 
let x = X { a: 1, b: 2, c: 3, d: 4 }; 
let y = Y { a: 5, ..x };

if the fields that are missing from Y's struct initializer have the same names and types in X as in Y. This occurs very often and I often have to write code that pulls over many fields manually (e.g. to convert between structs with different (serde) attributes and to derive view structs from model structs etc.).. It would make sense to allow the above as syntactic sugar for this:

let y = Y { a: 4, b: x.b, c: x.c, d: x.d };

So the compiler would:

  1. determine the set of fields missing from the initializer syntax ({ b: u16, c: u32, d: i8 } above)
  2. check if those fields are present in the type of x with the same types

You may say "just impl From<X> for Y" but that's exactly where many of these patterns occur!

And usually I have to do conversion functions on the few fields that are not pulled over from x, so a proc-macro to derive From wouldn't work, because y.a would have a different type than x.a.

  1. Related to/more discussion on https://github.com/rust-lang/rfcs/issues/1975

    Austin Bonander at 2018-01-26 11:38:28

  2. Triage: Broad feature request, should be moved the RFCs repo.

    Leonardo Yvens at 2018-03-02 23:14:59

  3. At least x as Y would be good, wouldn't it?

    Igor Strebz at 2023-02-26 22:56:43