我昨天在 github issue 上問過,其中一位貢獻者說我應該在這個站點上問它,所以我只是將我的問題粘貼到 stackoverflow 上。
您使用的是哪個版本的 Go ( go version)?
$去版本 轉到版本 go1.17.1 windows/amd64
這個問題會在最新版本中重現嗎?
是的
您使用的是什么作業系統和處理器架構 ( go env)?
go env 輸出$去環境
你做了什么?
我撰寫了簡單的代碼來嘗試描述現實世界,但是“不允許匯入回圈”會編譯錯誤。所以我只能把簡單的代碼改寫成復雜的代碼。
“不允許回圈匯入”是一個正確的原則,但不是讓代碼變得簡單的原則,而是讓代碼變得更復雜的原則。
它是臨時原則還是永久原則?
是經過多次思考和討論后設計的,還是只是為了個人喜好?
我問這個問題,因為我認為在現實世界中,一切都是自然而然地相互作用的。
例如,一個老師進一個教室,很多學生進一個教室,然后老師選擇學生a問,然后學生b問老師。這是一個正常的簡單要求。
但是在 golang 中,下面的代碼無法編譯成功,因為不允許匯入回圈。這太奇怪了。
testgo
│ main.go
│
├─classroom
│ ClassRoom.go
│
├─student
│ Student.go
│
└─teacher
Teacher.go
// main.go
package main
import (
"testgo/classroom"
"testgo/student"
"testgo/teacher"
)
func main() {
c := &classroom.ClassRoom{}
t := &teacher.Teacher{}
a := &student.Student{}
b := &student.Student{}
t.Enter(c)
a.Enter(c)
b.Enter(c)
t.Ask(a)
b.Ask(t)
print(c)
}
// classroom/ClassRoom.go
package classroom
import (
"testgo/student"
"testgo/teacher"
)
type ClassRoom struct {
Teacher *teacher.Teacher
Students []*student.Student
}
func (c *ClassRoom) AddTeacher(t *teacher.Teacher) {
c.Teacher = t
}
func (c *ClassRoom) AddStudent(s *student.Student) {
c.Students = append(c.Students, s)
}
// teacher/Teacher.go
package teacher
import (
"testgo/classroom"
"testgo/student"
)
type Teacher struct {
TeacherName string
InClassRoom *classroom.ClassRoom
}
func (t *Teacher) Enter(c *classroom.ClassRoom) {
c.AddTeacher(t)
t.InClassRoom = c
}
func (t *Teacher) Ask(s *student.Student) {
}
// student/Student.go
package student
import (
"testgo/classroom"
"testgo/teacher"
)
type Student struct {
StudentName string
InClassRoom *classroom.ClassRoom
}
func (s *Student) Enter(c *classroom.ClassRoom) {
c.AddStudent(s)
s.InClassRoom = c
}
func (s *Student) Ask(t *teacher.Teacher) {
}
最后,它會編譯錯誤,如下所示
package testgo
imports testgo/classroom
imports testgo/student
imports testgo/classroom: import cycle not allowed
還有更多的例子。
在現實世界中,貓捉老鼠,老鼠逃離貓。package Cat進口package Rat,package Rat進口package Cat。
在現實世界中,動物吃水果,水果被動物吃掉。package Animal進口package Fruit,package Fruit進口package Animal。
在現實世界中,進口周期無處不在。
但是在 golang 中,不允許匯入回圈。
你期待看到什么?
啟用匯入回圈,就像現實世界一樣
你看到了什么?
不允許匯入周期
uj5u.com熱心網友回復:
這是正確且經過深思熟慮的校長。如果您了解并吸收您的用例,則可以避免回圈。例如:-學生班級應該只有學生相關的詳細資訊、姓名、年齡、地址等。班級應該有容量、地址等內容。應該有一個名為 schedule.go 的單獨班級,用于保存班級、學生的映射和老師。
uj5u.com熱心網友回復:
這是一個永恒的原則。回圈依賴會增加編譯時間,而 GO 高度關注快速編譯時間。
回圈依賴的解決方案是在新包中引入新介面。該介面應該具有回圈依賴結構具有并被其他回圈依賴結構訪問的所有方法。
我找到了關于它的明確說明https://medium.com/@ishagirdhar/import-cycles-in-golang-b467f9f0c5a0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343536.html
上一篇:我想為dig創建界面
