elixir

get_in for nested list & struct in elixir


I have a structure

s = [
  a: %Bla{
   b: "c"
  }
]

I want to take c value from it. I'm trying to do

get_in(s, [:a, :b])

But it's not designed to take value from the struct. Is there any analogue which allows me to fetch c from the list with nested struct?


Solution

  • As documented, get_in does not work with structs by default:

    The Access syntax (foo[bar]) cannot be used to access fields in structs, since structs do not implement the Access behaviour by default. It is also design decision: the dynamic access lookup is meant to be used for dynamic key-value structures, like maps and keywords, and not by static ones like structs.

    There are two ways to achieve what you want:

    1. Implement Access behaviour for your struct.

    2. Use Access.key(:foo) instead of :foo.

    I would use (2):

    iex(1)> defmodule Bla do
    ...(1)>   defstruct [:b]
    ...(1)> end
    iex(2)> s = [a: %Bla{b: "c"}]
    [a: %Bla{b: "c"}]
    iex(3)> get_in(s, [:a, Access.key(:b)])
    "c"