A role has many accounts and an account has many roles.
How to simulate that avoiding the import cycle?
Inside my $GOROOT
sandbox/
├── hello-world.go
├── orm
│ ├── main
│ │ └── main.go
│ └── model
│ ├── account
│ │ └── account.go
│ └── role
│ └── role.go
cat sandbox/orm/main/main.go
package main
import (
"sandbox/orm/model/account"
)
func main() {
a := account.Account
}
cat sandbox/orm/model/account/account.go
package account
import (
"sandbox/orm/model/role"
)
type Account struct {
id int
roles []role.Role
}
cat sandbox/orm/model/role/role.go
package role
import (
"sandbox/orm/model/account"
)
type Account struct {
id int
roles []role.Role
}
Interestingly, you can avoid importing package by making use of go:linkname . go:linkname is compiler directive (used as //go:linkname localname [importpath.name] ).
Import cycles are the result of a design error. Structs which depend on each other in both directions must be in the same package, or else an import cycle will occur.
This is addressed in "Cyclic dependencies and interfaces in golang", in particular:
Replace import-requiring object types in APIs with basic types and interface.
Or put them in the same package.
I showed an example in "“Mutual” package import in Golang".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With