duanpin9531 2016-07-20 09:35
浏览 230

如何在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>
  • 写回答

3条回答 默认 最新

  • dsshsta97935 2016-07-20 09:53
    关注

    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"])
    }
    
    评论

报告相同问题?