我有一个结构
s = [
a: %Bla{
b: "c"
}
]
我要带
c
从中产生的值(value)。我正在尝试做get_in(s, [:a, :b])
但它并非旨在从结构中获取值(value)。是否有任何类似物可以让我获取
c
从带有嵌套结构的列表中?
最佳答案
如 documented , get_in
默认情况下不适用于结构:
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.
有两种方法可以实现您想要的:
Access
您的结构的行为。Access.key(:foo)
而不是 :foo
.我会使用(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"
关于elixir - get_in 用于 elixir 中的嵌套列表和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39855454/