有没有办法将记录与结构进行模式匹配?例如,给出下面的记录和结构。
struct = %User{name: "", twitter:""}
record = {User, "mossplix ", "@mossplix"}
答案 0 :(得分:10)
您需要手动匹配字段
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
或者您需要先将其转换为结构,然后匹配两个
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