英文:
Golang accessing parent package values in child package
问题
你好,我认为我遇到了一个接口/结构问题。我知道Go语言不支持继承,我在解决import cycle not allowed
错误时有些困惑。
在我的实际代码中,我在pkg A
中定义了一个结构体,我想在pkg C
中访问它。我看到应该使用接口来实现这个,但我不知道应该如何做。
例如,我有以下内容:
pkg A
是父包
pkg B
是子包
pkg C
是另一个子包
import pkg B
B.test1() // 访问来自pkg B的方法
pkg B
import pkg C
import pkg A
C.test2() // 访问来自pkg C的方法
pkg C
import pkg A
// 这会导致导入循环错误
A.Field1 // 尝试从父包访问结构体值```
<details>
<summary>英文:</summary>
Hello i think i am running into an interface/struct problem. I know go doesn't support inheritance and im kind of stomp on figuring this `import cycle not allowed` bug.
In my actual code I have defined a struct inside `pkg A` that I want to access in `pkg C` . Im seeing i should use interfaces to accomplish this but I don't know how I should do this.
For example I have something like
`pkg A` is the parent
`pkg B` is the child
pkg C` is another child
```pkg A
import pkg B
B.test1() // accessing method from pkg B
pkg B
import pkg C
import pkg A
C.test2() // accessing method from pkg C
pkg C
import pkg A
// This results in a import cycle error
A.Field1 // Trying to access a struct value from the parent package```
</details>
# 答案1
**得分**: 3
由软件包导入描述的依赖图必须是无环的,因此你遇到的错误信息是“不允许导入循环”。
例如,如果软件包`Alpha`导入软件包`Bravo`,而软件包`Bravo`导入软件包`Charlie`,那么软件包`Charlie`就不能导入软件包`Alpha`(或者`Bravo`),因为这会在依赖图中引入一个循环。
需要将共享的依赖项重构为另一个软件包,以消除循环。在上面的例子中,你可以重构软件包`Alpha`,将它和软件包`Charlie`都需要的部分提取到一个新的软件包`Delta`中,然后`Alpha`和`Charlie`都导入`Delta`。
<details>
<summary>英文:</summary>
The dependency graph described by package imports must be acyclic, hence the "import cycle not allowed" error message you're encountering.
If, for instance, package `Alpha` imports package `Bravo` and package `Bravo` imports package `Charlie`, package `Charlie` can't import package `Alpha` (or `Bravo` for that matter) because that would introduce a cycle into the dependency graph.
The shared dependency(ies) need to be refactored into another package so as to eliminate the cycle. In my above example, you might refactor package `Alpha` and extract the bits that both it and package `Charlie` need into a new package `Delta` that gets imported by both `Alpha` and `Charlie`.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论