1

此代码(在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 确实有田间水果。

4

1 回答 1

2

有几个问题。

首先,foodStruct确实有一个字段fruit,但f不是一个foodStruct。它是一个map[int]foodStruct,它根本没有任何字段或方法。

其次,没有任何地方f有 type map[int]map[int]string。如果不创建正确类型的新地图,就f无法传递 in 的任何部分。showFood

于 2012-10-14T06:58:40.713 回答