详解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)
    }
    
    func RequireB() {
      o := B.NewB()
      o.PrintB()
    }
    
    
  • packaga b:

    • package b
      
      import (
          "fmt"
          "githunb.com/mantishK/dep/a"
      )
      
      type B struct {
      
      }
      
      func (b B) PrintB() {
          fmt.Println(b)
      }
      
      func NewB() *B {
          b := new(B)
          return b
      }
      
      func RequirwA() {
          o := a.NewA()
          o.PrintA()
      
      }
    • 就会编译报错:

    • import cycle not allowed
      package github.com.mantishK/dep/a
          import github.com/mantidK/dep/b
          imort github.com/mantishK/dep/a
      • 现在的问题就是:

      • A depends on B
        B dependes on A
    • 那么如何避免?

    • 引入 package i,引入 intreface

      • 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

猜你喜欢

转载自www.cnblogs.com/jcjc/p/12454170.html