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:
I came here looking for a simple way to implement Access behaviour by all structs, but I agree with @NobbZ, it doesn’t make sense to do it for all structs.
So I thought of a simpler solution, just ‘unstructure’ those structs where I need to use get_in to access them deeply.
I made this little function:
def destructuring(struct) when is_struct(struct) do
struct |> Map.from_struct() |> destructuring
end
def destructuring(list) when is_list(list) do
list |> Enum.map(fn v ->
destructuring(v)
end)
end
def destructuring(map) when is_map(map) do
map |> Map.keys() |> Enum.reduce(%{}, fn (k,acc) ->
Map.put(acc, k, destructuring(map[k]))
end)
end
def destructuring(val), do: val
I’m new to elixir, but wouldn’t this be the same as doing this?
my_struct.x.y || "my_default"
Apart from this, I wonder how I could take advantage of get_in/1 in the case that the list of keys has to be generated dynamically based on certain logic?