如何在Go中创建map [string] [2] int? [重复]

This question already has an answer here:

I want to create a map[string][2]int in Go. I tried this at go playground but I got errors. How can I solve this?

fmt.Println("Hello, playground")
m:= make(map [string][2]int)
m["hi"]={2,3}
m["heello"][1]=1
m["hi"][0]=m["hi"][0]+1
m["h"][1]=m["h"][1]+1
fmt.Println(m)
</div>

Your map initialization is correct. You just need to explicitly declare the type of your map element:

m:= make(map [string][2]int)
m["test"] = [2]int{1,3}
fmt.Println(m)

This approach work if you don't need to access underlying elements.

If you need this, you have to use pointers:

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, playground")
    m := make(map[string]*[2]int)
    m["hi"] = &[2]int{2, 3}
    m["heello"] = &[2]int{0, 1}
    m["hi"][0] = m["hi"][0] + 1
    // commented out. Initialize it first
    //m["h"][1]=m["h"][1]+1
    fmt.Println(m) // 2 address
    fmt.Println(m["hi"], m["heello"])
}

You need to have a map of pointers to array if you want to be able to assign values to array indices. Check out this code (you need to initiate all map keys before using them as array though).

package main

import (
    "fmt"
)

func Assign(m map[string]*[2]int, key string, index int, value int) {
    if _, ok := m[key]; !ok {
        m[key] = &[2]int{}
    }

    m[key][index] = value
}

func main() {
    fmt.Println("Hello, playground")

    m := make(map[string]*[2]int)

    m["hi"] = &[2]int{2, 3}
    m["h"] = &[2]int{4, 5}

    //existing key
    Assign(m, "h", 1, 4)
    //new key
    Assign(m, "howdy", 1, 3)

    fmt.Println(m["hi"])
    fmt.Println(m["h"])
    fmt.Println(m["howdy"])

}

See this issue: https://github.com/golang/go/issues/3117

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, playground")
    m := make(map[string][2]int)

    m["hi"] = [2]int{2, 3}

    m["heello"] = [2]int{}

    var tmp = m["heello"]
    tmp[1] = 1
    m["heello"] = tmp

    fmt.Println(m)
}