英文:
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 "fmt"
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
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论