【问题标题】:Elixir - Create struct based on dynamic variableElixir - 基于动态变量创建结构
【发布时间】:2018-06-04 23:50:02
【问题描述】:

是否可以基于动态传递的变量创建结构?

类似的东西:

  def create_map_list(list, atom, struct) do
    Enum.filter(list, &Map.has_key?(&1, atom))
    |> Enum.map(
      &%struct{
        id: &1.new_agent.id,
        name: &1.new_agent.name,
        primary_skillset: &1.new_agent.primary_skillset,
        secondary_skillset: &1.new_agent.secondary_skillset
      }
    )

结束

【问题讨论】:

    标签: struct elixir


    【解决方案1】:

    是的,使用Kernel.struct/2

    iex(1)> defmodule A do
    ...(1)>   defstruct [:x]
    ...(1)> end
    iex(2)> [1, 2, 3] |> Enum.map(&struct(A, x: &1))
    [%A{x: 1}, %A{x: 2}, %A{x: 3}]
    

    在你的情况下,那将是:

    &struct(struct,
      id: &1.new_agent.id,
      name: &1.new_agent.name,
      primary_skillset: &1.new_agent.primary_skillset,
      secondary_skillset: &1.new_agent.secondary_skillset
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      相关资源
      最近更新 更多