golang anonymous field of type map

穿精又带淫゛_ 提交于 2019-12-07 09:28:01

问题


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:


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
}


来源:https://stackoverflow.com/questions/26447066/golang-anonymous-field-of-type-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!