Struct Pattern Matching in Arguments of Functions

From ElixirBlocks
Jump to: navigation, search

Example

%Person{} = person

defmodule Person do
  
  defstruct [
    first_name: nil,
    last_name: nil,
    birthday: nil,
    location: "home"
  ]

  def full_name(%Person{} = person) do
    "#{person.first_name} #{person.last_name}"
  end

  def age(%Person{} = person) do
    days = Date.diff(Date.utc_today, person.birthday)
    days / 365.25
  end

  def home(%Person{} = person) do
    %{person | location: "home"}
  end

  def away(%Person{} = person) do
    %{person | location: "away"}
  end
end