Is there a way to define an indexable type in golang?

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

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 分别称为 索引映射键。以下规则适用:
>
> 对于 数组类型 Aa:[...]
>
> 对于指向数组类型的 a:[...]
>
> 对于 切片类型 Sa:[...]
>
> 对于 字符串类型a:[...]
>
> 对于 映射类型 Ma:[...]
>
> 对于 类型参数类型 Pa:[...]
>
> 否则,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).

huangapple
  • 本文由 发表于 2022年7月8日 17:49:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/72909615.html
匿名

发表评论

匿名网友

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

确定