Go中的字典

huangapple go评论91阅读模式
英文:

Dictionary in Go

问题

我刚开始学习Go语言,之前使用Python,现在我想找到Go中与Python中的字典相当的数据结构。在Python中,我会这样做:

d = {
    'name': 'Kramer',  # 字符串
    'age': 25          # 整数
}

我最初找到了map类型,但它只允许一种类型的值(不能同时处理intstring)。我真的需要每次都创建一个struct吗?还是我漏掉了某种类型?

英文:

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 a type I'm missing?

答案1

得分: 38

基本上问题是,在实际代码中,很难遇到需要在同一个映射实例中存储不同类型的值的要求。

在你的特定情况下,你应该使用结构体类型,像这样:

type person struct {
  name string
  age  int
}

初始化它们与使用映射一样简单,多亏了所谓的“字面量”:

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

访问单个字段与使用映射一样简单:

joe["name"] // 一个映射

joe.name // 一个结构体类型

总的来说,请考虑阅读一本关于Go的入门书籍,以及在解决Go问题时,尽量运用你的工作知识。因为你不可避免地试图将你对动态类型语言的工作知识应用到严格类型的语言中,所以你基本上是在尝试用Go编写Python,这是逆向的。

我建议从《The Go Programming Language》开始阅读。

还有一些关于Go的免费书籍可供参考:Go的免费书籍

英文:

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 recommend starting with
The Go Programming Language.

There are also free books on Go.

答案2

得分: 11

这可能不是最好的决定,但你可以使用interface{}来使你的映射接受任何类型:

package main

import (
    "fmt"
)

func main() {
    dict := map[interface{}]interface{} {
        1: "hello",
        "hey": 2,
    }
    fmt.Println(dict) // map[1:hello hey:2]
}
英文:

That's probably not the best decision, but you can use interface{} to make your map accept any types:

package main

import (
    "fmt"
)

func main() {
    dict := map[interface{}]interface{} {
        1: "hello",
        "hey": 2,
    }
    fmt.Println(dict) // map[1:hello hey:2]
}

huangapple
  • 本文由 发表于 2017年9月6日 01:14:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/46060238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定