Access behavior / protocol / macro for custom type

I’m creating a custom type and I need to define original logic for the square bracket operator. How do I go about doing this? Do I use defimpl to define a protocol, or write a macro, or use Access behavior? Or some combination thereof?

1 Like

You should just need to implement the access behaviour: Access — Elixir v1.11.4


@LostKobrakai my struct is a table, so I need the brackets to take two indices. Would I implement this using syntax like [a][b] or [a, b]? I guess I’m still confused how behavior gets implemented. For example, let’s say I want to define access to also support a range for the index, so I could use an index (for the column) and a range for the row (to produce the enumerable for the subset of rows from the given column).

Okay, I see now that Access.get/3 is invoked when I use the square bracket, but in some cases it calls Access.fetch/2, so I don’t get this. I was able to implement fetch/2 so that I can use my_table[{0, 0}] to get the first entry from the first column, but [0, 0] would be a lot nicer.

I see this now, getting educated on how elixir works.

If you look at put_in, update_in or pop_in those brakets could also invoke different callbacks of the behaviour besides fetch/2. As you’ve noticed those brackets are a way for you to supply a key to be used. That key can be any term, but as you’ve seen it needs to be one term not many.

1 Like