:books: Today I Learned

How to get the default values out of an Elixir struct

programming Elixir elixir

Define a struct with some default values:

defmodule Person do
  defstruct [:name, age: 18]
end

Structs have a __struct__/0 function that returns the struct with its defaults values:

Person.__struct__()  # %Person{age: 18, name: nil}

Since structs are maps, you can extract each default value with Map.get/3:

defaults = Person.__struct__()
Map.get(defaults, :age)   # 18
Map.get(defaults, :name)  # nil

You can also use the static access operator (see Map/struct access in Writing assertive code with Elixir):

defaults = Person.__struct__()
defaults.age   # 18
defaults.name  # nil