在go中合并两个(相同类型的)结构?

I am kind of stuck here. I want to write a (generic, if possible!) function which will merge two structs of the same type - which also might contain not just primitives, but structs, and even slices.

Due to the constraints that are placed on us at the business level, we can't really use mergo, so I need to write this. But I am kind of having trouble getting any results worth talking about - I am not looking for a fully working solution (if you have code, it'll help for sure) but I really need some guidance on what this algorithm might look like.

I'd imagine I want to do something like have :

func Merge(source CustomStruct, target CustomStruct) result CustomStruct{

    // Maybe some kind of son work to get my two structs to be strings?

    // Iterate the JSON, comparing each field and taking values from source and target (depending on rules), and add them to result...

    // recursion for when it contains another struct, or slice?

    // return result
}

I guess there is a significant question here about performance. If performance matters, I can pretty much guarantee that serializing / deserializing to string representation isn't the way you want to go.

In general I'd assert that what you want to re: making it generic is not in the spirit of Go. If you need to "merge" two structs (itself an unclear objective without more specific examples) I think you probably should write this function yourself with explicit logic about which fields get copied where.

Work with product to reduce your use cases to a manageable number of types rather than trying to write something fully generic that can handle any imaginable type.

Then choose one of:

  1. Code generation with templates that will be populated on a per-type basis (high performance),
  2. Interfaces with type assertions (good performance, somewhat tedious to write but make use of a good editor or use code generation with templates here as well), or
  3. Reflection (poor performance, greater complexity, and possibly still tedious)

If you can't get it down to a manageable number of types, a solution is still possible with reflection, but much more complex. If you reach this point, look to the standard library and popular open source packages that are able to handle any type for examples/inspiration, and be aware it will likely take a lot of work/time/thought to complete and thoroughly test.