Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

What is a circular reference?

Circular references are a common problem encountered by go developers. A circular reference is A reference to B in package A, B in package C, and C in package A. When the project is compiled, A circular reference error will be reported.

Talk is easy, show me the code.

We define three files HelloA, HelloB, and HelloC.


package A

import (

"fmt"

"go_learn/C"

)

func HelloA(a) {

C.HelloC()

fmt.Println("package A hello")}Copy the code

package B

import (

"fmt"

"go_learn/A"

)

func HelloB(a) {

A.HelloA()

fmt.Println("package B hello")}Copy the code

package C

import "C"

import (

"fmt"

"go_learn/B"

)

func HelloC(a) {

B.HelloB()

fmt.Println("package C hello")}Copy the code

package main

import (

"go_learn/A"

)

func main(a) {

A.HelloA()

}

Copy the code

Then execute the main function and find the following error:


package go_learn

imports go_learn/A

imports go_learn/C

imports go_learn/B

imports go_learn/A: import cycle not allowed

Copy the code

Thus, circular references are attributed to errors in GO!

Why doesn’t GO support circular references?

Rob Pike, the father of the Go language, once answered this question by saying:

  • The code design of circular reference is unreasonable and does not consider the structure of the code well;

  • Circular references are not supported in order to force Go programmers to think more about application dependencies and keep dependency diagrams clean;

  • It also allows projects to build quickly.

What are the disadvantages of circular referencing?

First, circular references can certainly lead to a slow program build.

Second, if the project of a circular reference, then existed between module and call each other, along with the advancement of the project, the dependencies between modules will be more and more, resulting in two modules coupling becomes more and more high, by blurring the boundaries between the first end are coupled together, become a mess.

In addition, circular references can lead to infinite recursion, which can cause other problems.

How do I avoid circular references?

It is very important to design the code structure!!

Reference documentation

  • Why doesn’t Go support circular references?

  • Why doesn’t the Go language allow loop introductions?