前言
golang不允許循環(huán)import package ,如果檢測(cè)到 import cycle ,會(huì)在編譯時(shí)報(bào)錯(cuò),通常import cycle是因?yàn)樵O(shè)計(jì)錯(cuò)誤或包的規(guī)劃問(wèn)題。
以下面的例子為例,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()
}
就會(huì)在編譯時(shí)報(bào)錯(cuò):
import cycle not allowed
package github.com/mantishK/dep/a
imports github.com/mantishK/dep/b
imports github.com/mantishK/dep/a
現(xiàn)在的問(wèn)題就是:
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)
}
現(xiàn)在依賴關(guān)系如下:
A depends on B
B depends on I
C depends on A and B
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
您可能感興趣的文章:- 對(duì)Golang import 導(dǎo)入包語(yǔ)法詳解
- go各種import的使用方法講解
- golang 之import和package的使用
- MongoDB使用mongoexport和mongoimport命令,批量導(dǎo)出和導(dǎo)入JSON數(shù)據(jù)到同一張表的實(shí)例
- golang中import cycle not allowed解決的一種思路
- Golang報(bào)“import cycle not allowed”錯(cuò)誤的2種解決方法
- 如何解決django配置settings時(shí)遇到Could not import settings ''conf.local''
- Golang import 導(dǎo)入包語(yǔ)法及一些特殊用法詳解