前言
golang不允许循环import package ,如果检测到 import cycle ,会在编译时报错,通常import cycle是因为设计错误或包的规划问题。
以下面的例子为例,package a依赖package b,同事package b依赖package a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package a
import (
"fmt"
"github.com/mantishK/dep/b"
)
type A struct {
}
func (a A) PrintA() {
fmt.Println(a)
}
func NewA() *A {
a := new(A)
return a
}
func RequireB() {
o := b.NewB()
o.PrintB()
}
|
package b:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package b
import (
"fmt"
"github.com/mantishK/dep/a"
)
type B struct {
}
func (b B) PrintB() {
fmt.Println(b)
}
func NewB() *B {
b := new(B)
return b
}
func RequireA() {
o := a.NewA()
o.PrintA()
}
|
就会在编译时报错:
import cycle not allowed
package github.com/mantishK/dep/a
imports github.com/mantishK/dep/b
imports github.com/mantishK/dep/a
现在的问题就是:
A depends on B
B depends on A
那么如何避免?
引入package i, 引入interface
1
2
3
4
5
|
package i
type Aprinter interface {
PrintA()
}
|
让package b import package i
1
2
3
4
5
6
7
8
9
10
11
12
|
package b
import (
"fmt"
"github.com/mantishK/dep/i"
)
func RequireA(o i.Aprinter) {
o.PrintA()
}
|
引入package c
1
2
3
4
5
6
7
8
9
10
11
|
package c
import (
"github.com/mantishK/dep/a"
"github.com/mantishK/dep/b"
)
func PrintC() {
o := a.NewA()
b.RequireA(o)
}
|
现在依赖关系如下:
A depends on B
B depends on I
C depends on A and B
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。
原文链接:http://ju.outofmemory.cn/entry/230115