Skip to content

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

Open
@Boscop

Description

@Boscop

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions