Circular Import

Hi all,

I’m currently learning Golang and found out that unlike some programming languages, Golang doesn’t allow us to have a circular import. I found out this article Why Circular Import Is Illegal In Go | Jauhar's Blog explaining why that’s the case. AFAIK, circular import is not allowed because the init function can become an infinite recursive function.
My question is, is the article above accurate?

Well, circular dependencies are not allowed in any language, even though in some they are transparently removed if found. That’s because circular dependencies lead to an infinite loop.

I’ve read the article and tbh I can’t confirm it accuracy is at 100%. First of all the author states other languages allow circle imports. Out of the list he gives, I can tell that Python 100% doesn’t allow this. Examples are also required some more clarification. All in all, circle imports is a bad practice and I’m lament if any of the languages allows it implicit or explicit. It can lead to a lot of hidden errors and misunderstandings

Here’s a quote from Rob Pike explaining it:

The lack of import cycles in Go forces programmers to think more about their dependencies and keep the dependency graph clean and builds fast. Conversely, allowing cycles enables laziness, poor dependency management, and slow builds. Eventually one ends up with a single cyclical blob enclosing the entire dependency graph and forcing it into a single build object. This is very bad for build performance and dependency resolution. These blobs are also take much more work to detangle than the is required to keep the graph a proper DAG in the first place.

This is one area where up-front simplicity is worthwhile.

Import cycles can be convenient but their cost can be catastrophic. They should continue to be disallowed.

Not much else needs to be said.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.