4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GoでMap(map[string]interface{})を結合する

Last updated at Posted at 2019-10-23

Goでmap[string]interface{}を結合したいとき、 mergo ライブラリを使うとシンプルに結合できる。

map[string]interface{} を使う場合

m1 := map[string]interface{}{
    "a": 0,
    "b": 1,
}
m2 := map[string]interface{}{
    "a": 2,
    "c": 3,
}
mergo.Merge(&m1, m2)
// Will print
//map[string]interface {}{"a": 0, "b": 1, "c": 3}

mergo.Mergeの他に、 mergo.MergeWithOverwrite などもあるが略。

struct を使う場合

デフォルトの方法

type Foo struct {
	A string
	B int64
}

func main() {
	src := Foo{
		A: "one",
		B: 2,
	}
	dest := Foo{
		A: "two",
	}
	mergo.Merge(&dest, src)
// Will print
Foo{
  A: "two",
  B: 2,
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?