匿名结构,结构{}{}和{}的区别

Anonymous struct, difference between struct{}{} and {}

我在 golang 中定义了 stringstruct 的映射,定义如下:

var Foo = map[string]struct{}{
    "foo": struct{}{},
}

Gogland 默认将此声明标记为警告,表示 "Redundant type declaration".

var Foo = map[string]struct{}{
    "foo": {},
}

上面的代码解决了警告,但是我找不到任何关于 struct{}{}{} 声明之间区别的信息。有点像 "short notation" 吗?

https://play.golang.org/p/0Akx98XtB4

这个:

struct{}{}

是一个 composite literal,它包含类型 (struct{}) 和文字的值 ({})。

这个:

{}

也是一个复合文字没有类型,只有值。

通常你必须在复合文字中指定/包含类型,让编译器知道你正在创建哪种("type" 的)复合文字,因此语法是:

CompositeLit = LiteralType LiteralValue .

但是,当您指定一个映射复合文字时,键和值的类型从映射类型中已知,因此如果您打算指定这些类型的值,则可能会被省略。 Spec: Composite literals:

中提到了这一点

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.

(注:due to an oversight, this is only valid from Go 1.5.)