在Golang中,{}表示一个空的代码块或空的结构体字面量。

huangapple go评论85阅读模式
英文:

What is {} in Golang?

问题

我在讲义中看到了这个代码片段:

setCollection := map[string]struct{}{
	"uniqElement1": {},
	"uniqElement2": {},
	"uniqElement3": {},
}

据我理解,这里的{}表示空结构体,但我以前从未见过这种写法。这个写法总是表示空结构体吗?还有,在什么情况下可以使用这种表示法?下面这段代码是无效的:

setCollection["newElem"] = {}
英文:

I came across this in lecture notes:

setCollection := map[string]struct{}{
		"uniqElement1": {},
		"uniqElement2": {},
		"uniqElement3": {},
}

As I understand, {} here represents the empty struct, but I never saw this before. Does this always mean an empty struct? Also, when can we use this notation? This code doesn't work:

setCollection["newElem"] = {}

答案1

得分: 1

{}复合字面值的语法要求。

你的第一个示例使用复合字面值创建了一个映射值,并且在该字面值内部使用了其他结构体字面值作为映射的键值。规范允许在内部字面值中省略内部字面值的类型:

> 在数组、切片或映射类型 T 的复合字面值中,如果元素或映射键本身是复合字面值,则可以省略相应的字面值类型,如果它与 T 的元素或键类型相同。类似地,如果元素或键的类型是 *T,则可以省略 &T

你的第二个示例尝试在非复合字面值中使用 {},编译器不知道你想使用的类型。因此,这是一个编译时错误。你必须在第二个示例中明确指定类型:

setCollection["newElem"] = struct{}{}

其中 struct{} 是类型,struct{}{} 是一个复合字面值(类型为 struct{})。

参考链接:https://stackoverflow.com/questions/45122905/how-do-struct-and-struct-work-in-go/45123114#45123114

英文:

{ and } are syntax requirement of composite literal values.

Your first example uses a composite literal to create a map value, and inside that literal it uses other struct literals for the key values of the map. And the Spec allows to omit the inner type in the inner literal:

> 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. Similarly, elements or keys that are addresses of composite literals may elide the &T when the element or key type is *T.

Your second example tries to use {} not in a composite literal, and the compiler does not know what type you want to use. So it's a compile time error. You have to be explicit in the second example:

setCollection["newElem"] = struct{}{}

Where struct{} is the type, and struct{}{} is a composite literal value (of type struct{}).

See related: https://stackoverflow.com/questions/45122905/how-do-struct-and-struct-work-in-go/45123114#45123114

huangapple
  • 本文由 发表于 2022年4月12日 21:01:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/71843233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定