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