此代码(位于Go Playground的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)"
}
印刷:
pear
orange
有什么办法可以将变量f的形式传递给showFood(),以使其显示“梨”?传递f.fruit会引发上面注释行中所示的编译错误。这个错误令我感到困惑,因为foodStruct确实有野果。
相关分类