I have two or more structs (same type) that I need to merge into one in a given direction (c -> b -> a)... The merging simply replaces values in "a" by values in "b" unless it is a None option.
It is easy to write a function for that, but the problem is that it is a struct with nested structs, and it'll take a lot of time / a lot of code to do that.
I thought about a clever way and realised that I can serialise both structs via serde_json and write a recursive function that loops over key/values and overrides "a" by "b" unless the "b" value is Value::Null.
It is clever but not really, since serialising and deserialising just for this... Do you have any better ideas?
This probably can be done by macro, but that would be some giant, super complicated macro....
While not very easy, it is possible to write procedural macros producing iterators (including mutable ones) over the fields of the struct. Such macros would require a separate crate, but such extra crate can just be placed inside your parent crate.
The path looks thorny, but depending on how involved you are in the project, it may make sense to try. This would open for you a corner of Rust not often visited.
I don't like "vibe coding" and all such, but this is one case where stupid LLMs shine. I had a case very much like this one and the AI generated correct (always check it) code in 30 seconds. Boring, repetitive tasks are perfect for computers.
Do you mean just writing the field assignments out? Only you were replying to a comment suggesting macros yet described it as boring repetitive work.
I agree they are pretty good at writing out code like this even in the braindead completion mode, but it's knowing it's going to be kept up to date that's the question. If it's big enough that you don't want to write it by hand, it's big enough to be hard to discover you're missing an update somewhere, which would be really annoying to find.
Macros solve that, but at the cost of harder to understand code. There's a tipping point somewhere between writing by hand and a macro though...
In my case I was merging 2 structs into a new one and the generated code would break when adding or removing a field, so I just went with it. But I agree with you,l; if I'd have multiple instances of the same problem (multiple structs, etc) I'd probably try and write a macro.