模式匹配 Elixir Record Aganist 结构

Pattern Matching Elixir Record Aganist Struct

有没有办法将记录与结构进行模式匹配?例如,给定一条记录和下面的结构。

struct = %User{name: "", twitter:""}
record = {User, "mossplix ", "@mossplix"}

您要么需要手动匹配字段

defmodule Test do
  def foo(%User{name: name, twitter: twitter}, {User, name, twitter}) do
    IO.puts "match :)"
  end

  def foo(_struct, _record) do
    IO.puts "no match :("
  end
end

或者需要先转成struct再匹配两者

defmodule Test do
  def foo(struct, record) do
    do_foo struct, user_record_to_struct(record)
  end

  defp user_record_to_struct({User, name, twitter}) do
    %User{name: name, twitter: twitter}
  end

  defp do_foo(struct, struct) do
    IO.puts "match :)"
  end

  defp do_foo(_struct1, _struct2) do
    IO.puts "no match :("
  end
end