」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Go 中的匿名結構:何時在 `map[string]struct{}` 中指定類型是多餘的?

Go 中的匿名結構:何時在 `map[string]struct{}` 中指定類型是多餘的?

發佈於2024-11-08
瀏覽:326

 Anonymous Struct in Go:  When is it Redundant to Specify the Type in `map[string]struct{}`?

匿名結構:揭示struct{}{} 和{} 之間的差異

在Go 中,聲明字串到匿名結構映射可以透過兩種方式完成:

var Foo = map[string]struct{}{
    "foo": struct{}{},
}
var Foo = map[string]struct{}{
    "foo": {},
}

雖然兩個表達式都有效,但第二個表達式在 Gogland 中引發了有關「冗餘類型聲明」的警告。為了澄清這一點,讓我們探討一下這兩種形式之間的根本差異。

首先,考慮以下內容:

struct{}{}

這是一個複合文字由型別(struct{}) 及其值({} ) 組成。相較之下,這:

{}

是一個複合文字,省略類型並僅保留值。

通常,複合文字需要包含類型規格可協助編譯器識別其預期類型。根據語言規格:

CompositeLit = LiteralType LiteralValue .

但是,在定義對應複合文字時,鍵和值型別已由對應型別指定。因此,如果您打算提供這些指定類型的值,則可以省略類型規格。

這種省略受到Go 規範的認可,其中規定:

"Within a composite literal of array, slice, or map type T, elements or map keys that are themselves composite literals may elide the respective literal type if it is identical to the element or key type of T."
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3