作为匿名结构成员的映射

huangapple go评论75阅读模式
英文:

maps as anonymous struct members

问题

我在go语言中遇到了一些问题,我完全无法理解并且任何解释都会受到欢迎:

上面的代码将无法编译,会出现“unexpected map”错误。
这可能是因为结构体字段声明必须是类型,但我无法理解为什么“map[string]string”不是一种类型。

将其更改为

type Embedded map[string]string

type Test struct{
Name string
Embedded
}

可以避免编译器错误,但是Test["someKey"]仍然会引发编译器错误“invalid operation: Test["someKey"] (index of type Test)”。

当然,直接使用Test.Embedded["someKey"]来访问匿名字段是可以的,
但我的问题是:

  • 为什么在非匿名字段声明中,字面量map声明是有效的类型,但在匿名字段中却无效?
  • 为什么索引包含类型不起作用?为什么它不能起作用?

谢谢解答。

英文:

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

得分: 2

  1. 匿名字段 必须是命名类型。你可能有些混淆了 TypeLiteralTypeTypeName

  2. 根据规范,引用匿名字段必须始终使用其类型名称。因此,Test.Embedded[key] 是唯一合法的形式。在这里,你可能混淆了从嵌入字段继承的嵌入字段方法(无需使用字段名称)和字段值(必须使用字段名称)。

英文:
  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.

huangapple
  • 本文由 发表于 2013年8月2日 17:33:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/18013476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定