前言
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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。