Merge Two Structs

I have two Config structs:

  • The first is constructed from a json file read in via Serde.
  • The second is constructed from arguments parsed by StructOpt.

I've tried applying struct update syntax to merge them, but it didn't work:

let stored_config: Config = // ...
let passed_config: Config = // ...
let merged: Config = Config { ..stored_config, ..passed_config };

The compiler warns cannot use a comma after the base struct because it expects the ..stored_config to come last.

I can't find any method that would merge them.

I'm most familiar with javascript, and would typically write a spread like:

const storedConfig = {};
const passedConfig = {};
const merged = { ...storedConfig, ...passedConfig };

Or use a method like Object.assign:

// ...
const merged = Object.assign({}, storedConfig, passedConfig);

This is my first rust program. I apologize in advance if I'm missing something obvious.

1 Like

FRU syntax in rust only accepts one base struct. It's no a general expansion syntax.

Thank you for clarifying that!

If two struct's values can't be merged with FRU, is there a different way to do so?

There's no fast syntax.

Also, I take it all the fields in the structs are Options? I'm guessing that in javascript one of them would have had undefineds or something that the merge would have just ignored?

All are Options with the exception of a few bools.

I had to make --password a bool because when it was an Option, structopt wanted me to pass a value, and I am taking no value and instead reading in a value with dialoguer.

Javascript will override any values to the left with any values to the right. I was originally trying to do something similar where passed values override stored values which override default values.

I'm interested to learn the rust way, though :slight_smile:

IMHO, I would implement a merge method on the struct by hand. Something like this: Rust Playground

If the Config type is defined outside of your crate, you can write an extension trait for it.

3 Likes

I was actually just now trying to implement a merge method, and to be honest it wasn't going so well. Your rust playground link helped fill in the blanks. Thank you so much!

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.