Golang在子包中访问父包的值

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

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&#39;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&#39;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 &quot;import cycle not allowed&quot; error message you&#39;re encountering.

If, for instance, package `Alpha` imports package `Bravo` and package `Bravo` imports package `Charlie`, package `Charlie` can&#39;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>



huangapple
  • 本文由 发表于 2022年8月23日 01:40:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/73449051.html
匿名

发表评论

匿名网友

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

确定