此代码(在http://play.golang.org/p/BjWPVdQQrS的 Go Playground 上):
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)"
}
印刷:
pear
orange
有什么方法可以将变量f的形式传递给 showFood(),以便它打印“梨”?传递 f.fruit 会引发上面注释掉的行中显示的编译错误。这个错误让我很困惑,因为 foodStruct 确实有田间水果。