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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法