简体   繁体   中英

Elixir - Create struct based on dynamic variable

Is it possible to create a struct based on a dynamically passed variable ?

Something like that:

  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
      }
    )

end

Yes, using 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}]

In your case, that would be:

&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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM