Liveview todo_trek Repo - pattern matching struct

Hi, I’m studying Chris Liveview Todo_Trek code and I came across this line todo_trek/repo.ex at main · chrismccord/todo_trek · GitHub

I can’t wrap my head around {struct, id}. How does it work? where does struct come from?

2 Likes
  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

Oh, I see thanks @codeanpeace

1 Like