Import cycle - cruisechang/wiki-golang GitHub Wiki
Golang forces programer do not cross import code.
If that a 'Import cycle' error occurred when compile.
In that case we need to modify our structure of program to avoid 'Import cycle'.
'Import cycle' forces us to struct a clear structure.
It's a good way make our code better.
But what if we got a 'Import cycle' error?
Method 1
Make a clear be-imported only file which is imported by other files.
So other files no need to import file with cycle error.
建立一個中介的介面檔。
把共用的struct放到這裡,供程式import。
使用類似delegate的方式,把程式引入這裡,供其他程式呼叫。
//Put common struc here.
type People struct{
name string
year int
}
//declare a func type
type delegateFoo func(id string, num int) error
//declare a var of delegateFoo.
var foo delegateFoo
//Set this var by other one.
func SetFoo(function delegateFoo) {
foo = function
}
//Another one can call var by this way.
func Foo (id string,num int){
foo(id,num)
}
Method 2