Is there a way to pattern match a record against a struct? E.g given a record and a struct below.
struct = %User{name: "", twitter:""}
record = {User, "mossplix ", "@mossplix"}
You either need to match the fields manually
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
or you need to convert it to a struct first and then match the two
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With