fireproofsocks

fireproofsocks

Example of implementing Access protocol (behaviour?) in Struct

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:

get_in(my_struct, [:x, Access.key(:y, "my_default)])

Where my struct was shaped something like

%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:

  1. Is there an example somewhere in some library that demonstrates how to implement the Access behaviour?
  2. 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?

Thanks as always!

Marked As Solved

kip

kip

ex_cldr Core Team

Wasn’t quite sure what you were after. Probably you wanted:

iex> my_struct = %MyStruct{x: %{y: "this thing"}}
%MyStruct{x: %{y: "this thing"}}
iex> get_in(my_struct, [Access.key(:x), Access.key(:y, "my_default")])
"this thing"

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:

iex> get_in(my_struct, [Access.key(:x), :y])                          
"this thing"

Also Liked

kip

kip

ex_cldr Core Team

I think you’ll find this will do the trick:

iex> get_in(my_struct, [Access.key(:x, Access.key(:y, "my_default"))])
%{y: "My Value"}

You can wrap struct keys in Access.key/2 if required without implementing the whole Access protocol.

nwjlyons

nwjlyons

If x is nil doing .y will raise a KeyError. get_in/1 wont raise a KeyError

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement