Golang导出类型

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

Golang exported type

问题

假设我有一个包含在包github.com/user/foo中的包:

foo/
  main.go (包 main)
  bar/
    bar.go (包 bar)

现在,在bar.go中,我想使用main.go中的一个导出类型。

package main
type FooBar struct {}

如果我尝试import "github.com/user/foo",我会得到循环导入不允许的错误。有没有其他方法可以做到这一点,而不是为bar创建自己的存储库,这是我不想要的。

英文:

Suppose I have a package within a package github.com/user/foo:

foo/
  main.go (package main)
  bar/
    bar.go (package bar)

Now, within bar.go I would like to use an exported type from main.go.

package main
type FooBar struct {}

If I try to import "github.com/user/foo" I get cycled imports not allowed error. Is there any way to do this, other than to create own repo for bar, which I don't want.

答案1

得分: 6

你可以像这样分开:

foo/
  main.go (包 main)
  foo/
    foo.go (包 foo)
  bar/
    bar.go (包 bar)

然后在 bar.go 中使用 import "path/foo/foo"

英文:

You can separate it like:

foo/
  main.go (package main)
  foo/
    foo.go (package foo)
  bar/
    bar.go (package bar)

then import "path/foo/foo" in bar.go

huangapple
  • 本文由 发表于 2014年8月22日 02:23:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/25433381.html
匿名

发表评论

匿名网友

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

确定