gpt4 book ai didi

go - 从包访问主结构

转载 作者:行者123 更新时间:2023-12-01 22:41:26 25 4
gpt4 key购买 nike

请考虑以下示例go代码,也位于此处:https://play.golang.org/p/ZcNy_crAg51

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!")
}
我可以在main.go中访问 foo.Auxstruct
是否可以朝另一个方向访问 main.SampleStruct包中的 foo
请说明如何/解释。

最佳答案

在Go中这是不可能的,因为这将导致循环依赖:play.ground导入play.ground/fooplay.ground/foo导入play.ground。 Go不允许此类循环依赖项,因为它们具有many disadvantages
有几种可能的解决方案:

  • 您可以将SampleStruct移到play.ground/foo包中。这样,您可以在SampleStruct中使用play.ground/foo并将其导入play.ground中。
  • 或者,将SampleStruct移到其自己的包中,例如play.ground/bar。这样,您可以将play.ground/bar导入play.ground/fooplay.ground
  • 关于go - 从包访问主结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62885871/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com