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.
CodePudding user response:
Its 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 ofT
.
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:
{}