Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any good advice about how to avoid import cycle in Go?

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.

like image 478
Reck Hou Avatar asked Apr 23 '13 11:04

Reck Hou


People also ask

How do you avoid cyclic import in go?

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.

How do I fix import cycle not allowed in test?

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.

What is import cycle?

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.


1 Answers

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.

like image 151
zzzz Avatar answered Oct 06 '22 00:10

zzzz