get_in用于嵌套列表& lix剂中的结构 [英] get_in for nested list & struct in elixir
问题描述
我有一个结构
s = [
a: %Bla{
b: "c"
}
]
我想参加 c
的价值。我正在尝试
I want to take c
value from it. I'm trying to do
get_in(s, [:a, :b])
但这并不是为了从结构中获取价值。有没有类似的方法可以让我从带有嵌套结构的列表中获取 c
?
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?
推荐答案
已记录, get_in
默认情况下不适用于结构:
As documented, get_in
does not work with structs by default:
Access语法(foo [bar])不能用于访问结构中的字段,因为结构默认情况下不实现访问行为。这也是设计决策:动态访问查找旨在用于动态键值结构(如地图和关键字),而不用于静态结构(如结构)。
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:
-
实施
访问权限
使用 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"
这篇关于get_in用于嵌套列表& lix剂中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!