golang匿名字段的类型图

编程入门 行业动态 更新时间:2024-10-28 05:27:19
本文介绍了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匿名字段的类型图

本文发布于:2023-07-30 16:29:01,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   类型   golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!