引用另一个结构体会出现“未定义”的错误。

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

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
	}

}

huangapple
  • 本文由 发表于 2016年8月16日 02:32:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/38960858.html
匿名

发表评论

匿名网友

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

确定