从主包中导入变量/常量到子包中。

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

Import vars/consts from main in subpackage

问题

我有一个Go项目,位于**$GOPATH/dalu/myproject**,包含以下文件:

main.go:

package main

import "dalu/myproject/subpackage"
var GV string = "World"

func main() {
    subpackage.Hello()
}

subpackage/subpackage.go:

package subpackage

import (
    "fmt"
    "dalu/myproject"
)

func Hello() {
    //? fmt.Println("Hello"+GV)
}

奖励(如果可以的话):
我尝试了类似的更多子包的情况,当我尝试在主包中导入一个导入另一个子包的子包时,会出现"import cycle not allowed"的错误提示。

英文:

I have a Go project at $GOPATH/dalu/myproject with the following files :

main.go:

package main

import "dalu/myproject/subpackage"
var GV string = "World"

func main() {
    subpackage.Hello()
}

subpackage/subpackage.go:

package subpackage

import (
    "fmt"
    "dalu/myproject"
)

func Hello() {
    //? fmt.Println("Hello"+GV)
}

Bonus (if I could):
I tried something similar with more subpackages and when trying to import a subpackage in main that imports another subpackage which imports the first mentioned subpackage I get "import cycle not allowed"

答案1

得分: 44

正如编译器所说,Go语言不允许循环依赖,与C++不同,这里没有可以使用前向声明的技巧。

如果你有这样的情况:
A 导入 B 并且 B 导入 A

这意味着你需要将它们之间共享的内容移动到包 C 中,并进行如下操作:
A 导入 B、C 并且 B 导入 C

这样每个人都会很开心!

或者在你的例子中,添加一个名为 dalu/myproject/gv/gv.go 的文件,并在其中定义 GV。然后在 mainsubpackage 中导入它。

英文:

As the compiler so nicely said, Go doesn't allow cyclic dependencies, and unlike C++ there are no forward declarations tricks to be done here.

if you have a state where:
A imports B AND B imports A

it measns you need to move whatever they share between them to package C, and do:
A imports B, C AND B imports C

and everyone's happy!

or in your example, add a file called dalu/myproject/gv/gv.go and in it define this GV. Then import it in both main and subpackage

huangapple
  • 本文由 发表于 2014年1月18日 22:54:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/21205696.html
匿名

发表评论

匿名网友

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

确定