Golang does not allow circular import issues ("Import cycle not allowed")

Source: Internet
Author: User

Golang does not allow circular import package, if the import cycle detected, will be wrong in the compile times, usually import cycle is due to design errors or package planning problems.
In the example below, package a relies on package B, colleague Package B relies on package a
Package A

Import (
"FMT"

"Github.com/mantishk/dep/b"
)

Type A struct {
}

Func (a) PrintA () {
Fmt. Println (a)
}

Func Newa () *a {
A: = new (a)
Return a
}

Func Requireb () {
o: = B.NEWB ()
O.PRINTB ()
}

Package B:

Package B

Import (
"FMT"

"GITHUB.COM/MANTISHK/DEP/A"
)

Type B struct {
}

Func (b) Printb () {
Fmt. Println (b)
}

Func newb () *b {
B: = new (b)
Return b
}

Func Requirea () {
o: = A.newa ()
O.printa ()
}

Would be wrong in compiling the Times:
Import Cycle not allowed
Package github.com/mantishk/dep/a
Imports Github.com/mantishk/dep/b
Imports GITHUB.COM/MANTISHK/DEP/A

Now the question is:
A depends on B
B depends on A

So how to avoid it?
Introducing package I and introducing interface
Package I

Type Aprinter Interface {
PrintA ()
}

Let package B Import Package I
Package B

Import (
"FMT"

"Github.com/mantishk/dep/i"
)


Func Requirea (o i.aprinter) {
O.printa ()
}

Introduction of Package C
Package C

Import (
"GITHUB.COM/MANTISHK/DEP/A"
"Github.com/mantishk/dep/b"
)

Func Printc () {
o: = A.newa ()
B.requirea (o)
}

Now the dependencies are as follows:
A depends on B
B depends on I
C depends on A and B

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.