前言
golang不允許循環(huán)import package ,如果檢測到 import cycle ,會在編譯時報錯,通常import cycle是因為設(shè)計錯誤或包的規(guī)劃問題。
以下面的例子為例,package a依賴package b,同事package b依賴package a
package aimport ( "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 bimport ( "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
現(xiàn)在的問題就是:
A depends on B
B depends on A
那么如何避免?
引入package i, 引入interface
package itype Aprinter interface { PrintA()}
讓package b import package i
package bimport ( "fmt" "github.com/mantishK/dep/i")func RequireA(o i.Aprinter) { o.PrintA()}
引入package c
package cimport ( "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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答
圖片精選