Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "import cycle" in a n--n relationship

Tags:

go

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
}
like image 534
José Neta Avatar asked Nov 10 '14 10:11

José Neta


People also ask

How to avoid import cycle in Go?

Interestingly, you can avoid importing package by making use of go:linkname . go:linkname is compiler directive (used as //go:linkname localname [importpath.name] ).

What is import cycle?

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.


1 Answers

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".

like image 114
VonC Avatar answered Sep 18 '22 01:09

VonC