I stumbled across the desire to want to use get_in while accessing deeply nested parts of a custom struct while needing to provide a default value. I could make a simple defp function to achieve this, but I wanted to see how to handle it using the Access protocol, so I tried something like this:
%MyStruct{x: %{y: "My Value"}}
# or maybe
%MyStruct{x: %{}}
This results in an error:
** (UndefinedFunctionError) function MyStruct.fetch/2 is undefined (MyStruct does not implement the Access behaviour)
I have 2 followup questions to this:
Is there an example somewhere in some library that demonstrates how to implement the Access behaviour?
I’ve read somewhere that structs don’t implement this behaviour for performance reasons – what considerations should be made before implementing the behavior in a struct?
Note that since :x is just a map you can do the following if you don’t need to supply a default (which you shouldn’t have to so since this is about a struct: