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

Reck Hou picture Reck Hou · Apr 23, 2013 · Viewed 26.8k times · Source

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.

Answer

zzzz picture zzzz · Apr 23, 2013
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.