簡體   English   中英

為什么 Golang 允許在全局 scope 但不允許在 function scope 中循環引用

[英]Why Golang allows circular reference in global scope but not in function scope

當我使用gormigrate編寫數據庫遷移時,我需要在 function scope 中定義兩個結構之間的多對多關系。 但在 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")
}

但是,將定義移到 function 之外就可以了

package main

import "fmt"

type Student struct {
    Courses []*Course
}
type Course struct {
    Students []*Student
}

func main() {
    fmt.Printf("This works")
}

可以在https://go.dev/play/p/GI53hhlUTbk自己嘗試一下

為什么會這樣? 我怎樣才能讓它在 function scope 中工作?

C++中是否有類似typedef的語法,所以我們可以先聲明一個struct,然后再定義它?

謝謝!

package中可以使用循環類型引用,但不能在 function 中使用。 規范中關於聲明和范圍的部分說:

  1. 表示常量、類型、變量或 function(但不是方法)的標識符的 scope 在頂層(任何函數之外)聲明是 ZEFE90A8E604A7C840E88D03A67F6B78D。

  1. 在 function 中聲明的類型標識符的 scope 開始於 TypeSpec 中的標識符,並結束於最里面的包含塊的末尾。

function 中類型的 scope 從類型聲明開始。 package塊中的scope是整個package。

沒有一種方法可以聲明一個類型的名稱,然后再定義該類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM