hpopp
Access Behaviour on Structs
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on structs.
https://github.com/codedge-llc/accessible
So, while I know this goes directly against core design decisions, it makes it extremely simple to perform deeply nested gets/updates on complex structs. This is something I could see myself using on every major project from now on.
I’ve found relatively little discussion about it, so I’m wondering, have I done something dirty?
Most Liked Responses
mguimas
You can use put_in and get_in on structs like shown by Dogbert in Elixir: best practice to extract data from nested structs on Stackoverflow.
christhekeele
I think core’s design decision in this regard is twofold:
- The compile-time guarantees of
struct.fieldaccess should be strongly encouraged over the runtimestruct[:field]form - The creator of the struct might have a different vision for what
Accessmight mean for their data-structure
This is why it’s not a part of core—I don’t think that means that it should be avoided within your own structs, though, especially if they nest other data-structures you intend for your struct’s users to interact with manually.
An example of the second point might be a Conn struct that represents key/value access to an external system, like redis or an API. It’s going to want to define Access for itself, but with radically different intentions than exposing its actual literal fields.
lkuty
Looks like it is for protocols, not behaviours. I think I will use struct_access to avoid copy/pasting:
@behaviour Access
defdelegate get(v, key, default), to: Map
defdelegate fetch(v, key), to: Map
defdelegate get_and_update(v, key, func), to: Map
defdelegate pop(v, key), to: Map
Note that the pop function might better be implemented as below to silently ignore the request to delete the key. Or we might want to raise.
def pop(v, key), do: {v[key], v}








