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

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

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

问题

我有以下的目录结构:

github.com
    meee
      projectA
        foo
         foo.go
        bar
         bar.go

在 foo.go 文件中:

package foo

import(
  "github.com/meee/projectA/bar"
)
type Foo struct {
  Name string
  Bars []Bar
}

在 bar.go 文件中:

package bar

type Bar struct {
  Name string
}

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

undefined: Bar

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

英文:

I have the following dir structure:

github.com
    meee
      projectA
        foo
         foo.go
        bar
         bar.go

In foo.go:

package foo

import(
  "github.com/meee/projectA/bar"
)
type Foo struct {
  Name string
  Bars []Bar
}

In bar.go:

package bar

type Bar struct {
  Name string
}

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

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包也是一样的。现在应该可以这样使用:

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

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:

type Foo struct {
    Name string
    Bars []bar.Bar
}

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:

确定