英文:
Passing a Go map that is in a structure
问题
package main
import "fmt"
type foodStruct struct {
fruit map[int]string
veggie map[int]string
}
func showFood(f map[int]map[int]string) {
fmt.Println(f[1][1])
}
func main() {
f := map[int]foodStruct{
1: {
fruit: map[int]string{1: "pear"},
veggie: map[int]string{1: "celery"},
},
}
fmt.Println(f[1].fruit[1])
g := map[int]map[int]string{1: map[int]string{1: "orange"}}
showFood(g)
}
英文:
This code (at Go Playground at http://play.golang.org/p/BjWPVdQQrS):
package main
import "fmt"
type foodStruct struct {
fruit map[int]string
veggie map[int]string
}
func showFood(f map[int]map[int]string) {
fmt.Println(f[1][1])
}
func main() {
f := map[int]foodStruct{
1: {
fruit: map[int]string{1: "pear"},
veggie: map[int]string{1: "celery"},
},
}
fmt.Println(f[1].fruit[1])
g := map[int]map[int]string{1: map[int]string{1: "orange"}}
showFood(g)
// showFood(f.fruit) // Compile error: "f.fruit undefined (type map[int]foodStruct has no field or method fruit)"
}
prints:
pear
orange
Is there any way I can pass a form of variable f to showFood(), so that it prints "pear"? Passing f.fruit raises the compile error shown in the commented-out line above. The error is confusing to me, since foodStruct does have field fruit.
答案1
得分: 2
首先,foodStruct确实有一个字段fruit,但是f不是一个foodStruct。它是一个map[int]foodStruct,它根本没有任何字段或方法。
其次,在f中没有任何类型为map[int]map[int]string的内容。没有办法将f的任何部分传递给showFood,除非创建一个正确类型的新映射。
英文:
There are a couple problems.
First, foodStruct does have a field fruit, but f is not a foodStruct. It's a map[int]foodStruct, which doesn't have any fields or methods at all.
Second, nowhere in f is there anything that has the type map[int]map[int]string. There's no way to pass any part of f into showFood without creating a new map of the correct type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论