Dispatching custom `getindex` method

I have a Vector, say xs. I also have a const CustomType = Int. Basically I want to index xs with CustomType values. Easy enough with xs[custom_mapping(i)]. Is there a way to leverage the type system so I can write xs[i] where i::CustomType? It seems I can not use the “const” method, because CustomType will be evaluated to Int: which means an eventual getindex(Vector, Int) method call (which is not what I want).

The only way I can come up with is wrapping the vector in a struct. Is there a more idiomatic/clean way? If I do use a struct, is there a performance penalty? Maybe I’m missing something obvious…

I would really like to use x[i] syntax since my code is indexing specific locations pretty heavily. Thanks in advance for any feedback!

You can either use what you figured out, wrapping your vector in a struct and defining indexing for it, or you can wrap Int in a struct:

struct CustomType

And define a getindex(x::AbstractArray,i::CustomType) method.

1 Like