Using a custom struct as a type in another struct in Go not building

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

Using a custom struct as a type in another struct in Go not building

问题

我有以下的目录结构:

  1. github.com
  2. meee
  3. projectA
  4. foo
  5. foo.go
  6. bar
  7. bar.go

在 foo.go 文件中:

  1. package foo
  2. import(
  3. "github.com/meee/projectA/bar"
  4. )
  5. type Foo struct {
  6. Name string
  7. Bars []Bar
  8. }

在 bar.go 文件中:

  1. package bar
  2. type Bar struct {
  3. Name string
  4. }

这段代码无法编译/构建,我得到的错误是:

  1. undefined: Bar

由于我已经导入了它,我不知道为什么它无法编译。

英文:

I have the following dir structure:

  1. github.com
  2. meee
  3. projectA
  4. foo
  5. foo.go
  6. bar
  7. bar.go

In foo.go:

  1. package foo
  2. import(
  3. "github.com/meee/projectA/bar"
  4. )
  5. type Foo struct {
  6. Name string
  7. Bars []Bar
  8. }

In bar.go:

  1. package bar
  2. type Bar struct {
  3. Name string
  4. }

This will not compile/build, the error I get is:

  1. undefined: Bar

Since I have it imported, I do not know why it will not compile.

答案1

得分: 4

如果你导入了fmt包,就不能直接调用Println函数。你必须使用fmt.Println来调用,否则会出现undefined: Println错误。

对于你的bar包也是一样的。现在应该可以这样使用:

  1. type Foo struct {
  2. Name string
  3. Bars []bar.Bar
  4. }
英文:

If you import fmt, you cannot call Println directly. You must call fmt.Println instead; otherwise, you get the undefined: Println error.

It's the same for your bar package. This should work now:

  1. type Foo struct {
  2. Name string
  3. Bars []bar.Bar
  4. }

huangapple
  • 本文由 发表于 2014年12月21日 04:43:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/27584163.html
匿名

发表评论

匿名网友

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

确定