”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Go 中的匿名结构:什么时候在 `map[string]struct{}` 中指定类型是多余的?

Go 中的匿名结构:什么时候在 `map[string]struct{}` 中指定类型是多余的?

发布于2024-11-08
浏览:966

 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