Liveview todo_trek Repo - pattern matching struct

  def multi_transaction_lock(multi, name, %struct{id: id}) when is_integer(id) do
    multi_transaction_lock(multi, name, {struct, id})
  end

Elixir lets you pattern match out the name of the struct and assign it to a value within the function head itself. Take a look at foo and bar in the example below.

defmodule Example, do: defstruct [:id]
defmodule Pattern, do: def match(%foo{id: bar}), do: IO.puts("foo = #{foo} & bar = #{bar}")

Pattern.match(%Example{id: "1"})
=> foo = Elixir.Example & bar = 1

For more, here’s another relevant forum post:

6 Likes