LoginSignup
40
32

More than 5 years have passed since last update.

Goで多重連想配列

Last updated at Posted at 2015-09-26

Go言語で多重連想配列を実現したいとします。
一次元の連想配列はこの記法で問題なく動作するのですが…。

test := make(map[string]int)
test["a"] = 1
test["b"] = 2

同じように多次元連想配列を実現しようとして下記のような書き方をするとpanicが発生します。

test := make(map[string]map[string]map[string]int)
test["a"]["a"]["a"] = 1
test["a"]["a"]["b"] = 2

多次元連想配列を実現するには、最下層より前まで都度makeしてやらないといけないようです。
2次元連想配列の場合、下記のような書き方で解決できます。

// 2次元連想配列
test2 := make(map[string]map[string]int)
test2["a"] = make(map[string]int)
test2["a"]["a"] = 1 // ok
test2["a"]["b"] = 2 // ok
test2["b"]["b"] = 3 // これはpanic。test["b"] = make(map[string]int)してからならok

3次元連想配列ならこう。

// 3次元連想配列
test3 := make(map[string]map[string]map[string]int)
test3["a"] = make(map[string]map[string]int)
test3["a"]["a"] = make(map[string]int)
test3["a"]["a"]["a"] = 1 // ok
test3["a"]["a"]["b"] = 2 // ok
test3["a"]["b"]["b"] = 3 // panic。test["a"]["b"] = make(map[string]int)してからならok
40
32
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
40
32