英文:
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
。然后在 main
和 subpackage
中导入它。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论