传递一个在结构体中的Go map

huangapple go评论77阅读模式
英文:

Passing a Go map that is in a structure

问题

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)

}

英文:

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

得分: 2

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

其次,在f中没有任何类型为map[int]map[int]string的内容。没有办法将f的任何部分传递给showFood,除非创建一个正确类型的新映射。

英文:

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.

huangapple
  • 本文由 发表于 2012年10月14日 14:47:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/12879965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定