英文:
Referencing another struct gives "undefined"
问题
我有一些非常简单的golang代码:
func main() {
type config struct {
interval int `mapstructure:"Interval"`
statsdPrefix string `mapstructure:"statsd_prefix"`
groups []group
}
type group struct {
group string `mapstructure:"group"`
targetPrefix string `mapstructure:"target_prefix"`
targets []target
}
}
当我运行这段代码时,我得到以下错误信息:
undefined: group
我在这里漏掉了什么?
英文:
I have some very simple golang code:
func main (){
type config struct {
interval int `mapstructure:"Interval"`
statsdPrefix string `mapstructure:"statsd_prefix"`
groups []group
}
type group struct {
group string `mapstructure:"group"`
targetPrefix string `mapstructure:"target_prefix"`
targets []target
}
}
When I run this, I get the following:
undefined: group
What am I missing here?
答案1
得分: 2
由于您在函数中定义了类型,因此在有组类型引用之前,配置类型定义会运行。调整定义的顺序可以解决问题,尽管我不得不删除对目标的引用,因为您没有提供它的定义。
以下是调整后的代码示例,可以在playground上运行:https://play.golang.org/p/fzRCtCHqnH
func main() {
type group struct {
group string `mapstructure:"group"`
targetPrefix string `mapstructure:"target_prefix"`
}
type config struct {
interval int `mapstructure:"Interval"`
statsdPrefix string `mapstructure:"statsd_prefix"`
groups []group
}
}
英文:
Since you've defined the types in a function, the config type definition runs before there is a group type to reference. Reversing the order of your definitions works, although I had to remove the reference to target as you have not provided it's definition.
This works in the playgound https://play.golang.org/p/fzRCtCHqnH:
func main() {
type group struct {
group string `mapstructure:"group"`
targetPrefix string `mapstructure:"target_prefix"`
}
type config struct {
interval int `mapstructure:"Interval"`
statsdPrefix string `mapstructure:"statsd_prefix"`
groups []group
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论