I'm working on a Go project for a month. The good thing is Go is really highly efficient. But after a month of development I've already got thousands lines of code and many packages
. To avoid import cycle is a major issue for me that anytime I got a import cycle error, I have no idea where the problem may be at first time.
The Go compiler also only have very simple notice that always not good enough to locate issue quickly like: main.go:7:3: import cycle not allowed
. It will only help you to know which file may cause the problem but nothing more deeply. Since import
relationship just become more and more complex while code grows, I'm eager to know how to avoid import cycle more efficiently in Go. Any help is much appreciated.
To avoid the cyclic dependency, we must introduce an interface in a new package say x. This interface will have all the methods that are in struct A and are accessed by struct B.
According to above explanation, put the tests within the same package will always got into the import cycle problem, and the solution is to move it to another package.
Explanation: Import cycles. It is possible to write packages so that package A imports package B and package B imports package A. ... If you make sure that, in any import cycle, at least one of the imports is in the implementation part of a package, you will not encounter any trouble.
go list -f '{{join .Deps "\n"}}' <import-path>
Will show import dependencies for package at <import-path>
- or in current directory if <import-path>
is left empty. Alternatively
go list -f '{{join .DepsErrors "\n"}}' <import-path>
hopefully shows some useful information in your case. See also the output of
go help list
for additional information about the go list tool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With