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

Time:07-08

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?

CodePudding user response:

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

  •  Tags:  
  • go
  • Related