Golang匿名字段的类型为map。

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

golang anonymous field of type map

问题

我以为通过使用匿名字段,我可以创建一个有序映射类型:

type customMap struct{
    map[string]string
    ordered []string
}

这样我就可以通过customMapInstance["key"]引用映射,并遍历ordered。然而,看起来数组和映射不是有效的匿名字段。我怀疑这背后有一个很好的原因...

英文:

I thought I'd be able to make an ordered map type by using anonymous fields:

type customMap struct{
    map[string]string
    ordered []string
}

where I could reference the map with customMapInstance["key"] and iterate over ordered. Alas, it appears arrays and maps are not valid anonymous fields. I suspect there's a good reason...

答案1

得分: 8

从规范中可以看出:

>嵌入类型必须指定为类型名T或非接口类型名*T的指针,并且T本身不能是指针类型。

你可以看到它提到了“类型名”。

>命名类型由(可能带限定符的)类型名指定;未命名类型使用类型字面量指定,它由现有类型组成一个新类型。

换句话说,除非将map或slice定义为命名类型,否则它们不能是匿名的。例如:

type MyMap map[string]string

type customMap struct{
    MyMap
    ordered []string
}

然而,即使嵌入了MyMap或slice类型,你仍然无法对customMap进行索引。只有字段和方法可以在嵌入时“提升”。对于其他所有情况,它们都只是另一个字段。在上面的示例中,MyMap没有任何字段或方法,因此等效于:

type customMap struct{
    MyMap MyMap
    ordered []string
}
英文:

From the spec:

>An embedded type must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type.

You see that it mentions a "type name".

>Named types are specified by a (possibly qualified) type name; unnamed types are specified using a type literal, which composes a new type from existing types.

In other words, a map or slice may not be anonymous unless they are defined as a named type. For example:

type MyMap map[string]string

type customMap struct{
    MyMap
    ordered []string
}

However, even if you embed MyMap or a slice type, you would still not be able to index customMap. Only fields and methods may be "promoted" when you embed. For everything else they act as just another field. In the above example, MyMap doesn't have any fields or methods and therefore is equivalent to:

type customMap struct{
    MyMap MyMap
    ordered []string
}

huangapple
  • 本文由 发表于 2014年10月19日 11:41:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/26447066.html
匿名

发表评论

匿名网友

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

确定