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语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?