dsafq2131321
2012-10-14 06:47 浏览 27
已采纳

传递结构中的Go地图

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条回答 默认 最新

  • 已采纳
    dream_high1026 dream_high1026 2012-10-14 06:58

    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.

    点赞 评论 复制链接分享

相关推荐