Go语言:import cycle not allowed报错解决方案

import cycle not allowed

    • go语言中包的循环引用解决方法

go语言中包的循环引用解决方法

报错如下:
Go语言:import cycle not allowed报错解决方案_第1张图片
图一

golang是不支持包与包之间互相引用的,例如:
package a 包下的 a.go

package a

import "CircularReference/b"

func Add(a , b int ) int {
	return a + b
}

func Calculate() int {
	sum := b.Ride(2, 2) + Add(1, 2)
	return sum
}

package b 包下的 b.go

package b

import (
	"CircularReference/a"
)

func Ride(a, b int) int{
	return a * b
}

func Result() int {
	sum2 := a.Calculate()
	return sum2
}

最后,执行main.go

package main

import (
	"CircularReference/b"
	"fmt"
)

func main() {
	fmt.Println(b.Result())
}

得到图一错误

解决方案:
在项目再加一层 package c

Go语言:import cycle not allowed报错解决方案_第2张图片
如图,在项目中加一个package c,将package a和 package b 中被对方调用的方法体抽出来放在c.go中

package c

func Ride(a, b int) int{
	return a * b
}

func Add(a , b int ) int {
	return a + b
}

这样,package a和 package b 所需的方法将从package c中调,避免了循环引用

Go语言:import cycle not allowed报错解决方案_第3张图片

你可能感兴趣的:(Go语言进阶)