zoukankan      html  css  js  c++  java
  • 详解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
            
  • 相关阅读:
    淘宝返回顶部
    混合布局
    css布局使用定位和margin
    选项卡 js操作
    ul li 好友列表
    js添加删除元素
    下拉列表的简单操作
    python笔记
    kali linux 虚拟机网卡未启动
    python 重新安装pip(python2和python3共存以及pip共存)
  • 原文地址:https://www.cnblogs.com/jcjc/p/12454170.html
Copyright © 2011-2022 走看看