GoLang Empty Struct Construction

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

GoLang Empty Struct Construction

问题

有人可以解释一下为什么这段代码是有效的 Go 代码,但这段代码却无效吗?

m := map[string]struct{}{"hello": {}}
c := make(chan struct{}, 1)
c <- {}

在第一段代码中,似乎我可以通过{}来构造结构体,但在第二段代码中,我需要使用struct{}{}

英文:

Can someone explain why this

m := map[string]struct{}{&quot;hello&quot;: {}}

is valid go code but this

c := make(chan struct{}, 1)
c &lt;- {}

is not? It seems like I'm able to construct the struct via just {} in the first statement but I need to do struct{}{} for the second.

答案1

得分: 3

这是要翻译的内容:

这不是一比一的情况。如果你尝试这样做,你会得到相同的错误:

package main

func main() {
   m := make(map[string]struct{})
   m["hello"] = {} // 语法错误:意外的{,期望表达式
}

至于你更大的问题,我相信在这里已经回答了[1]:

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

所以例如,如果你有一个复合字面值:

map[string]struct{}

其中元素也是复合字面值:

struct{}

那么你可以省略类型:

{}
  1. <https://golang.org/ref/spec#Composite_literals>
英文:

It's not apples to apples. If you try this instead, you get same error:

package main

func main() {
   m := make(map[string]struct{})
   m[&quot;hello&quot;] = {} // syntax error: unexpected {, expecting expression
}

As to your greater question, I believe that is answered here [1]:

> 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.

So for example, if you have a composite literal:

map[string]struct{}

where elements are also composite literal:

struct{}

Then you can omit the type:

{}
  1. <https://golang.org/ref/spec#Composite_literals>

huangapple
  • 本文由 发表于 2021年10月27日 02:00:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/69727895.html
匿名

发表评论

匿名网友

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

确定