Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  C语言  >  正文 golang不允许循环import问题("import cycle not allowed")

golang不允许循环import问题("import cycle not allowed")

发布时间:2017-12-13   编辑:www.jquerycn.cn
jquery中文网为您提供golang不允许循环import问题("import cycle not allowed")等资源,欢迎您收藏本站,我们将为您提供最新的golang不允许循环import问题("import cycle not allowed")资源
本文章来为各位介绍关于golang不允许循环import问题("import cycle not allowed")问题的解决办法了,这个是语法问题各位可以来看看.

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

您可能感兴趣的文章:
golang不允许循环import问题("import cycle not allowed")
「golang系列」浅谈Go语言
Go 语言的核心优势
go语言有哪些优势?Go语言的核心特性有哪些
Go 语言循环语句
golang 切片截取 内存泄露_怎么看待Goroutine 泄露
php错误提示 open_basedir restriction in effect 解决
GOPROXY:解决 go get golang.org/x 包失败
go基础算法思想
Golang面试题总结

[关闭]