Elixir Tips

Elixir Tips

  • This is a common recurring lookup at my company, how to convert from a map to a struct and vice versa
    defmodule BestStructEver do
      defstruct [:a]
    end
    
    # Struct to simple map:
    
    iex> Map.from_struct(%BestStructEver{a: "foobar"})
    # => %{a: "foobar"}
    
    
    # Map to a struct:
    
    iex> struct(BestStructEver, %{a: "foobar"})
    # => %BestStructEver{a: "foobar"}
    
    
    # Note: The struct function is from Kernel, so `Kernel.` can be omitted.
    7 upvotes