#Update one struct values from another struct values

3 messages · Page 1 of 1 (latest)

uneven belfry
#
type MyModel struct {
  Age    int64
  Name   string
}

obj1 := MyModel{
  Age:  10,
  Name: "Go",
}

obj2 := MyModel{
  Name: "Python",
}

I want to create (or just update any one of the object) and keep the values from obj2 (for key which are present in it) and take the defaults from obj1.
So the result should be like:

{
  Age:  10.
  Name: "Python"
}

I can have multiple keys to update and take defaults of.

wet root
eager valve
#

You can't do that for struct, but python's dict and object is kind like Golang's map[string]any here. However you don't have a syntax or builtin method to help you to merge a map, so you have to make your own methods to merge stuffs.

Anyways, it's unreasonable to request a dynamic language feature appear in a static language, even in fact you can implement that in Go use "reflect"