英文:
Is there a way to define an indexable type in golang?
问题
我最近发现了一个通过直接索引(即graph[key]
)进行图处理的库。我有一个节点树,其中的子节点位于特定属性node.childs[key]
下面。
我想知道是否有一种方法可以定义一种类型,以便通过直接键映射来访问属性,例如node[key]
将映射到node.childs[key]
。在定义新类型时是否有实现这一点的方法?
英文:
I recently came across a library that does graph processing by direct indexing i.e graph[key]
, I have a node tree which has its child nodes under a certain attribute node.childs[key]
.
I was wondering if there is a way to define a type so that an attribute could be accessible through direct key mapping, such as node[key]
would be mapped to node.childs[key]
. Is there a way to achieve this while defining new types?
答案1
得分: 5
不,你想要的是不可能的。规范不允许这样做。规范:索引表达式:
> 形式为
>
> a[x]
>
> 的主表达式表示数组、指向数组的指针、切片、字符串或映射 a
中由 x
索引的元素。值 x
分别称为 索引 或 映射键。以下规则适用:
>
> 对于 数组类型 A
的 a
:[...]
>
> 对于指向数组类型的 a
:[...]
>
> 对于 切片类型 S
的 a
:[...]
>
> 对于 字符串类型 的 a
:[...]
>
> 对于 映射类型 M
的 a
:[...]
>
> 对于 类型参数类型 P
的 a
:[...]
>
> 否则,a[x]
是非法的。
只有列出的这些类型可以进行索引,其他类型都不行。而且你甚至不能改变索引运算符的含义(无法重载它)。
英文:
No, it's not possible to do what you want. The spec does not allow it. Spec: Index expressions:
> A primary expression of the form
>
> a[x]
>
> denotes the element of the array, pointer to array, slice, string or map a
indexed by x
. The value x
is called the index or map key, respectively. The following rules apply:
>
> For a
of array type A
: [...]
>
> For a
of pointer to array type: [...]
>
> For a
of slice type S
: [...]
>
> For a
of string type: [...]
>
> For a
of map type M
: [...]
>
> For a
of type parameter type P
: [...]
>
> Otherwise a[x]
is illegal.
Only these listed types are indexable, no other. And you can't even change the meaning of the index operator (you can't override it).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论