从包访问主结构 请考虑这个样本GO代码,也在这里:
我可以访问main.go中的从包访问主结构 请考虑这个样本GO代码,也在这里:,go,Go,我可以访问main.go中的foo.Auxstruct 是否可以转到另一个方向并访问包foo中的main.SampleStruct 请说明如何/解释。这在围棋中不可能,因为它会导致循环依赖:play.groundimportsplay.ground/foo和play.ground/fooimportsplay.ground。Go不允许这样的循环依赖,因为它们有 有几种可能的解决方案: 您可以将SampleStruct移动到play.ground/foo包中。这样,您可以在play.ground/
foo.Auxstruct
是否可以转到另一个方向并访问包foo
中的main.SampleStruct
请说明如何/解释。这在围棋中不可能,因为它会导致循环依赖:
play.ground
importsplay.ground/foo
和play.ground/foo
importsplay.ground
。Go不允许这样的循环依赖,因为它们有
有几种可能的解决方案:
SampleStruct
移动到play.ground/foo
包中。这样,您可以在play.ground/foo
中使用SampleStruct
,并将其导入play.ground
SampleStruct
移动到它自己的包中,例如play.ground/bar
。通过这种方式,您可以将play.ground/bar
导入play.ground/foo
和play.ground
不,因为循环依赖是不允许的。除了前面的评论之外,我建议您阅读这篇文章@bobra,内存模型的相关性并不明显。请解释一下。
package main
import (
"fmt"
"play.ground/foo"
)
type SampleStruct struct {
token int
}
var (
MainSampleVar = SampleStruct{token: 333}
)
func main() {
fmt.Println("Hello!")
b := foo.Auxstruct{AuxToken: 4333}
fmt.Printf("b: %#v\n", b)
foo.AuxHello()
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo
import "fmt"
type Auxstruct struct {
AuxToken int
}
func AuxHello() {
fmt.Println("Aux says hello!")
}