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

时间:2017-10-12 10:21:35

标签: dictionary go struct composite-literals

I have string to struct map in golang defined in the following way:

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

Gogland by default marks this declaration as warning, saying "Redundant type declaration".

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

Above code solves the warning, but I couldn't find any information about the difference between struct{}{} and {} declaration. Is it kind of a "short notation"?

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

1 个答案:

答案 0 :(得分:9)

此:

struct{}{}

composite literal,其中包含类型(struct{})和文字的值({})。

此:

{}

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

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

  

CompositeLit = LiteralType LiteralValue

但是,当您指定地图复合文字时,键和值的类型从地图类型中已知,因此如果您要指定这些类型的值,则可以省略。这在Spec: Composite literals:

中提到
  

在数组,切片或地图类型T的复合文字中,如果元素或映射键本身是复合文字,则它们可能会忽略相应的文字类型,如果它与{{1的元素或键类型相同}}。同样,当元素或键类型为T时,作为复合文字地址的元素或键可能会忽略&T

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