[英]Why Golang allows circular reference in global scope but not in function scope
As I'm writing DB migrations using gormigrate , I need to define a many-to-many relationship between two structs in a function scope.当我使用gormigrate编写数据库迁移时,我需要在 function scope 中定义两个结构之间的多对多关系。 But in golang 1.19 or 1.18 the following won't compile
但在 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")
}
However moving the definitions outside of the function will just work但是,将定义移到 function 之外就可以了
package main
import "fmt"
type Student struct {
Courses []*Course
}
type Course struct {
Students []*Student
}
func main() {
fmt.Printf("This works")
}
Can try this yourself at https://go.dev/play/p/GI53hhlUTbk可以在https://go.dev/play/p/GI53hhlUTbk自己尝试一下
Why is this the case?为什么会这样? And how can I make it work in a function scope?
我怎样才能让它在 function scope 中工作?
Is there a similar syntax to typedef in C++, so we can declare a struct first and then define it later? C++中是否有类似typedef的语法,所以我们可以先声明一个struct,然后再定义它?
Thanks!谢谢!
Circular type references are possible in the package block , but not inside a function. package块中可以使用循环类型引用,但不能在 function 中使用。 The section on Declarations and Scopes in the specification says:
规范中关于声明和范围的部分说:
- The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.
表示常量、类型、变量或 function(但不是方法)的标识符的 scope 在顶层(任何函数之外)声明是 ZEFE90A8E604A7C840E88D03A67F6B78D。
⋮
⋮
- The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.
在 function 中声明的类型标识符的 scope 开始于 TypeSpec 中的标识符,并结束于最里面的包含块的末尾。
The scope of a type in a function starts at the type declaration. function 中类型的 scope 从类型声明开始。 The scope of a type in the package block is the entire package.
package块中的scope是整个package。
There is not a way to declare the name of a type and later define the type.没有一种方法可以声明一个类型的名称,然后再定义该类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.