最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
golang不允许循环import问题("import cycle not allowed")
时间:2016-01-04 编辑:简简单单 来源:一聚教程网
golang不允许循环import package,如果检测到import cycle,会在编译时报错,通常import cycle是因为设计错误或包的规划问题。
以下面的例子为例,package a依赖package b,同事package b依赖package a
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:
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
package i
type Aprinter interface {
PrintA()
}
让package b import package i
package b
import (
"fmt"
"github.com/mantishK/dep/i"
)
func RequireA(o i.Aprinter) {
o.PrintA()
}
引入package c
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
相关文章
- C#复制数组的两种方式及效率比较解读 10-24
- ASP.NET Identity用法解析 10-24
- ASP.NET MVC使用Identity增删改查用户介绍 10-24
- C语言中atoi函数模拟实现介绍 10-18
- .Net反向代理组件Yarp用法介绍 10-10
- .NET使用YARP通过编码方式配置域名转发实现反向代理教程 10-10