Home > Article > Backend Development > Go import loops not allowed
php editor Strawberry is here to introduce an important rule to you: In the Go language, importing loops is not allowed. This means that when writing Go code, we cannot import the current package again within the imported package. This provision is to avoid the problem of circular dependencies and ensure the reliability and maintainability of the code. If we encounter a circular import situation when writing code, we need to re-examine our code structure and consider whether we need to refactor to avoid the occurrence of circular dependencies. By following this rule, we can write more robust and reliable Go code.
I am a newbie in go
and I am learning go
. I want this folder structure where model is the database entity,
Controller is where the endpoint is,
Service is where the actual functionality happens.
(The problem is the folder/package structure)
Course --- Course.controler.go --- Course.model.go --- course.service.go Faculty --- Faculty.controller.go --- Faculty.model.go --- Faculty.service.go
1 Teacher can have 0..* courses so I implemented the foreign key here by importing the teacher package
course.model.go
package course import ( "go-server/routes/faculty" "gorm.io/gorm" ) type Course struct { gorm.Model Name string `json:"name"` Code string `json:"code" gorm:"unique;size:192"` Year int `json:"year"` Description string `json:"description"` FacultyId int `json:"faculty"` Faculty faculty.Faculty `gorm:"foreignKey:FacultyId"` }Now if I implement a function called
GetCoursesForFacultyID(id) in
course.service.go
I can't use it on
faculty.service due to the import cycle. How can I overcome this problem?
Course --- Course.controler.go --- Course.service.go Faculty --- Faculty.controller.go --- Faculty.service.go Models --- Course.model.go --- Faculty.model.goor
School --- Course.controler.go --- Course.model.go --- Course.service.go --- Faculty.controller.go --- Faculty.model.go --- Faculty.service.go
The above is the detailed content of Go import loops not allowed. For more information, please follow other related articles on the PHP Chinese website!