golang匿名字段的类型图 [英] golang anonymous field of type map

查看:203
本文介绍了golang匿名字段的类型图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可以通过匿名字段创建一个有序的地图类型:

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

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

在那里我可以通过 customMapInstance [key] 来引用地图,并遍历命令。唉,它显示数组和地图不是有效的匿名字段。我怀疑有一个很好的理由......

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...

推荐答案

从规范:

From the spec:


嵌入类型必须指定为类型名称T或指向非接口类型名称T的指针,而T本身可能不是指针类型。 b $ b

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
}






但是,即使嵌入了MyMap或切片类型,您仍然无法为customMap编制索引。嵌入时只有字段和方法可能会被提升。对于其他任何事物,他们只是另一个领域。在上面的示例中,MyMap没有任何字段或方法,因此相当于:


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
}

这篇关于golang匿名字段的类型图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆