前言
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ì)腳本之家的支持。
標(biāo)簽:貴州 德宏 保定 曲靖 許昌 吐魯番 東營(yíng) 常州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《詳解golang避免循環(huán)import問(wèn)題(“import cycle not allowed”)》,本文關(guān)鍵詞 詳解,golang,避免,循環(huán),import,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。