Struct update syntax for different types


#1

Struct update syntax makes it easy to create a new struct reusing the data contained in an existing struct of the same type. Is there similar functionality for structs of different types, perhaps using macros?

I’d like to be able to do something like this:

#[derive(Debug)]
struct Foo {
    bar: i32,
    baz: i32,
}

#[derive(Debug)]
struct Qux {
    bar: i32,
}

fn main() {
    let spread = Qux { bar: 0 };
    let foo = Foo { baz: 2, ..spread };
    println!("{:?}", foo);
}

But obviously, this fails:

error[E0308]: mismatched types
  --> src/main.rs:15:31
   |
15 |     let foo = Foo { baz: 2, ..spread };
   |                               ^^^^^^ expected struct `Foo`, found struct `Qux`
   |
   = note: expected type `Foo`
              found type `Qux`

My use case is that I have input coming from different sources which gets parsed into different structs, and ultimately I want to merge these into a single struct which represents a database row and commit it to the database.


#2

Similar flexibility (of merging, adding, removing fields) is a common need in TypeScript/Clojure code, but currently it’s not much supported in Rust.


#3

Thanks, I hoped there might be a dark corner of syntax I hadn’t heard about, perhaps on nightly :slight_smile: But it doesn’t seem like it then. And macros can’t be used for a general solution (merging any two struct types) either, I didn’t quite think that one through.