英文:
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".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论