简体   繁体   English

Golang 访问子 package 中的父 package 值

[英]Golang accessing parent package values in child package

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.我知道 go 不支持 inheritance 并且我有点踩到这个import cycle not allowed的错误。

In my actual code I have defined a struct inside pkg A that I want to access in pkg C .在我的实际代码中,我在pkg A中定义了一个结构,我想在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是父pkg B是孩子 pkg C` 是另一个孩子


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```

The dependency graph described by package imports must be acyclic, hence the "import cycle not allowed" error message you're encountering. package 导入描述的依赖关系图必须是非循环的,因此您会遇到“不允许导入循环”错误消息。

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. 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.共享依赖项需要重构为另一个 package 以消除循环。 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 .在我上面的示例中,您可以重构 package Alpha并提取它和Alpha Charlie需要的位到新的Charlie Delta

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM