get_in for nested list & struct in elixir

て烟熏妆下的殇ゞ 提交于 2019-12-10 17:57:28

问题


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?


回答1:


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 protocol 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"



回答2:


Here is my version of try function to return values from both maps and structs:

def try(map, keys) do
  Enum.reduce(keys, map, fn key, acc -> if acc, do: Map.get(acc, key) end)
end


来源:https://stackoverflow.com/questions/39855454/get-in-for-nested-list-struct-in-elixir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!