elixir - get_in 用于 elixir 中的嵌套列表和结构

标签 elixir

我有一个结构

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/

    相关文章:

    javascript - Elixir 中的 OO 风格参数?

    elixir - 使用 Ueberauth 不断收到跨站点请求伪造错误

    elixir - Elixir 中的条件编译

    elixir - 混合 ecto.create 连接被拒绝

    elixir - 在 Ecto 中我什么时候应该使用 assoc_constraint 与foreign_key_constraint

    elixir - 如何限制监护人和 Phoenix 的特定操作的权限

    elixir - Elixir 的 Ecto : Foreign Key

    elixir - 处理 Phoenix 中的特定约束错误

    elixir - Elixir 中的最佳数据结构,可根据值进行频繁更新、项目删除和子集创建

    Elixir:模式匹配函数签名中的多个列表