如何避免 n-n 关系中的 “import cycle” 问题?

huangapple go评论87阅读模式
英文:

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

问题

一个角色可以有多个账户,一个账户可以有多个角色。

如何模拟以避免导入循环?

在我的$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
}

英文:

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
}

答案1

得分: 4

这在《Golang中的循环依赖和接口》中有所提及,特别是:

> 用基本类型和接口替换在API中需要导入的对象类型。

或者将它们放在同一个包中。

我在《Golang中的“相互”包导入》中展示了一个例子。

英文:

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

huangapple
  • 本文由 发表于 2014年11月10日 18:13:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/26841308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定