`map[string][]string` 和 `map[string]string` 之间的区别是什么?

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

What is the difference between map[string][]string and map[string]string?

问题

我注意到在**Go文档**中包含了这个定义:

type Values map[string][]string

起初我以为这是一个错误,但后来我尝试了这段代码并且它编译通过了(Playground):

package main

import "fmt"

func main() {
    type MyType map[string][]string

    foobar := make(MyType)

    fmt.Println(foobar)
}

它与map[string]string在功能上是等价的,或者说有什么区别吗?

英文:

I noticed in the Go docs this definition was included:

type Values map[string][]string

I thought it was a mistake, but then I tried this code and it compiles (<kbd>Playground</kbd>):

package main

import &quot;fmt&quot;

func main() {
	type MyType map[string][]string

	foobar := make(MyType)

	fmt.Println(foobar)
}

Is it functionally equivalent to map[string]string, or is there some difference?

答案1

得分: 9

它们是不同的。一个是字符串到字符串切片的映射,另一个是字符串到单个字符串的映射。

[][]string 中表示一个切片。

http://play.golang.org/p/nv7wSWW0F7

英文:

They are different. One is a map of strings to a slice of strings, vs a map of strings to a single string

The [] in []string denotes a slice

http://play.golang.org/p/nv7wSWW0F7

答案2

得分: 1

一个是字符串切片的映射,而另一个是字符串的映射。一个结构有一个维度,map[string][]string有两个维度。在每个键k上,切片中会有0到n个项目。因此,访问需要另一层级的指向,例如fmt.Println(myInts[k][0]),而不是fmt.Println(myInts[k])。将数据放入其中,差异将更加明显。

英文:

One is a map of string slices while the other is a map of strings. One structure has a single dimension, the map[string][]string has two. At every key k you'll have items 0-n in the slice. So access requires another level of direction like fmt.Println(myInts[k][0]) as apposed to fmt.Println(myInts[k]). Put data in it and the difference will be more apparent.

huangapple
  • 本文由 发表于 2015年8月5日 23:41:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/31837011.html
匿名

发表评论

匿名网友

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

确定