英文:
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{}{"hello": {}}
is valid go code but this
c := make(chan struct{}, 1)
c <- {}
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{}
那么你可以省略类型:
{}
- <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["hello"] = {} // 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:
{}
- <https://golang.org/ref/spec#Composite_literals>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论