Skip to content

Instantly share code, notes, and snippets.

@oyakata
Last active May 21, 2022 10:17
Show Gist options
  • Save oyakata/c41c3e9df39af69d4a049b6786b0808e to your computer and use it in GitHub Desktop.
Save oyakata/c41c3e9df39af69d4a049b6786b0808e to your computer and use it in GitHub Desktop.
Goでmapのマージ [Pythonのdict.update的な]
package main
import "fmt"
func mergeDict(xs ...map[string]interface{}) map[string]interface{} {
result := map[string]interface{}{}
for _, x := range xs {
for k ,v := range x {
result[k] = v
}
}
return result
}
func main() {
fmt.Println(mergeDict(
map[string]interface{}{"foo": 1},
map[string]interface{}{"bar": 2},
)) // map[foo:1 bar:2]
type Map map[string]interface{}
fmt.Println(mergeDict(
Map{"foo": 5, "bar": 12},
Map{"foo": 17, "baz": false},
)) // map[bar:12 baz:false foo:17]
}
package main
import (
"fmt"
"github.com/imdario/mergo"
)
func main() {
dct := map[string]interface{}{"foo": "par?"}
type Foo struct {
Foo, bar string // publicのフィールドしかマージされない
}
type Bar map[string]interface{}
foo := Foo{}
foo2 := Foo{"ga?", "par(f)"}
bar := Bar{}
// Bar * Bar 同じ型同士なのでok
fmt.Println(mergo.Merge(&bar, Bar{"foo": "1"})) // <nil>
// Bar * map[string]interface{} 型が違うのでエラー
fmt.Println(mergo.Merge(&bar, map[string]interface{}{"foo": "2"})) // src and dst must be of same type
// Foo * map[string]interface{} 型が違うのでエラー
fmt.Println(mergo.Merge(&foo, dct)) // src and dst must be of same type
// Foo * Foo 同じ型同士なのでok
fmt.Println(mergo.Merge(&foo, &foo2)) // <nil>
fmt.Println("***foo***", foo) // ***foo*** {ga? }
fmt.Println("***bar***", bar) // ***bar*** map[foo:1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment