Use reflection
You can update Model with reflection and reflect package .
The following function updates the old Model in place:
func (old *Model) MergeInPlace(new Model) { for ii := 0; ii < reflect.TypeOf(old).Elem().NumField(); ii++ { if x := reflect.ValueOf(&new).Elem().Field(ii); !x.IsNil() { reflect.ValueOf(old).Elem().Field(ii).Set(x) } } }
You would call this method by saying x.MergeInPlace(y) , where x and y are Model s. x will be changed after calling this function.
Sample output
The "merger" of the following,
{ "id":"1", "field1":"one", "field2":"two", "field3":"three" } { "id":"1", "field3":"THREE" }
gives:
{ "id":"1", "field1":"one", "field2":"two", "field3":"THREE" }
That is, it overwrites all the values โโpresent in the new structure in the old, ignoring the values โโthat are "undefined".
Obviously, you can Marshal (or not) as you wish.
Full program
See the full working example on the Go Playground.
The usual caveats apply (check returned production errors!).
source share