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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置