duai4512 2017-09-05 17:14
浏览 68
已采纳

Golang字典

I'm just starting out with Go, and coming from Python I'm trying to find the equivalent of a dict in Python. In Python I would do this:

d = {
    'name': 'Kramer',  # string
    'age': 25          # int
}

I first found the map type, but that only allows for one type of value (it can't handle both ints and strings. Do I really need to create a struct whenever I want to do something like this? Or is there any type I'm missing?

All tips are welcome!

  • 写回答

2条回答 默认 最新

  • dongze5043 2017-09-06 07:43
    关注

    Basically the problem is that it's hard to encounter a requirement to store values of different types in the same map instance in real code.

    In your particular case, you should just use a struct type, like this:

    type person struct {
      name string
      age  int
    }
    

    Initializing them is no harder than maps thanks to so-called "literals":

    joe := person{
      name: "Doe, John",
      age:  32,
    }
    

    Accessing individual fields is no harder than with a map:

    joe["name"] // a map
    

    versus

    joe.name // a struct type
    

    All in all, please consider reading an introductory book on Go along with your attemps to solve problems with Go, as you inevitably are trying to apply your working knowledge of a dynamically-typed language to a strictly-typed one, so you're basically trying to write Python in Go, and that's counter-productive.

    I'd recomment starting with The Go Programming Language.

    There are also free books on Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器