get_in and Access
  •  1 min read

Access.key

Get a value by key. Useful for structs that don't implement the Access behaviour.

defmodule Dog do
  defstruct [:name, :breed]
end

[dog: %Dog{name: "Gwen", breed: "Border Collie"}]
|> get_in([:dog, Access.key(:name)])

# "Gwen"

Access.all

Access all elements in a list.

defmodule Dog do
  defstruct [:name, :breed]
end

[
  dogs: [
    %Dog{name: "Gwen", breed: "Border Collie"},
    %Dog{name: "Clover", breed: "JRT"}
  ]
]
|> get_in([:dogs, Access.all(), Access.key(:name)])

# ["Gwen", "Clover"]

Access.at

Get an element from the list at an index.

[
  numbers: [
    [1, 2, 3, 4],
    [5, 6, 7, 8]
  ]
]
|> get_in([:numbers, Access.all(), Access.at(1)])

# [2, 6]