映射为匿名结构成员

I was stumbling over some behavior in go which I cannot make sense of completely and explainations of any kind would be wellcome:

type Test struct{
    Name string // or other metadata to be stored along the core map element
    map[string]string
}

The above code will fail to compile with an unexpected map error. Which is probably because struct Field delarations must be types, however I fail to appriciate why map[string]string is not a type.

Changing it to

type Embedded map[string]string

type Test struct{
    Name string
    Embedded
}

get's arround the compiler error, but still Test["someKey"] raises the compiler error invalid operation: Test["someKey"] (index of type Test).

Of course adressing the anoymous field directly with Test.Embedded["someKey"] works, but my questions are:

  • Why are literal map declarations valid as types in non-anonymous field declarations but not valid in anonymous fields
  • Why does indexing the containing type not work? Why can't it work?

Thanks for clarifications.

  1. Anonymous fields must be named types only. You're perhaps somewhat confusing Type, LiteralType and TypeName.

  2. Referring to an anonymous field is presribed by the specs to be done always by its type name. Thus Test.Embedded[key] is the only legal form. Here you might be confusing the embedded field methods, which are inherited from embedded fields w/o need to use the field name and the field value, which must use it.