当我使用gormigrate编写数据库迁移时,我需要在函数作用域中定义两个结构之间的多对多关系。但在 golang 1.19 或 1.18 中,以下内容将无法编译
package main
import "fmt"
func main() {
type Student struct {
Courses []*Course
// [Error] ./prog.go:7:14: undefined: Course
}
type Course struct {
Students []*Student
}
fmt.Printf("This won't compile")
}
Run Code Online (Sandbox Code Playgroud)
然而,将定义移到函数之外就可以了
package main
import "fmt"
type Student struct {
Courses []*Course
}
type Course struct {
Students []*Student
}
func main() {
fmt.Printf("This works")
}
Run Code Online (Sandbox Code Playgroud)
可以自己尝试一下https://go.dev/play/p/GI53hhlUTbk
为什么会这样呢?我怎样才能让它在函数范围内工作?
C++中是否有类似typedef的语法,所以我们可以先声明一个结构体,然后再定义它?
谢谢!