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 byx
. The valuex
is called the index or map key, respectively. The following rules apply:For
a
of array typeA
: [...]For
a
of pointer to array type: [...]For
a
of slice typeS
: [...]For
a
of string type: [...]For
a
of map typeM
: [...]For
a
of type parameter typeP
: [...]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).