harleyqmc
harleyqmc

Reputation: 11

What is the point of this ( reverse ) assignment / matching in this Elixir function

My only guess is that it is for verifying that it is a struct. otherwise what does %User{}= user do?

def change_user(%User{} = user) do
  User.changeset(user, %{})
end

It comes from the Phoenix framework and various generators etc...

Thanks in advance.

Upvotes: 1

Views: 194

Answers (2)

Everett
Everett

Reputation: 9568

It might help if you think of it more as type-hint. Although it is a pattern match, the syntax here reminds me of other languages (e.g. PHP, Python, or Go) that put data types in the function signatures.

But since it's Elixir, it IS a pattern match, and it is an idiomatic way to communicate the intent of that particular function clause or to set yourself up to define other function clauses. For example, imagine these function clauses defined alongside the example you provided:

def change_user(%LegacyUser{} = legacy_user) do
  LegacyUser.changeset(legacy_user, %{})
end

def change_user(arg) do
  Logger.error("Unsupported argument given to change_user/1: #{inspect(arg)}")
end

Although functionally, it doesn't matter if you do %User{} = user or user = %User{}, it is more idiomatic to use the former.

Upvotes: 1

zwippie
zwippie

Reputation: 15515

Yup, that will just verify that the input can be matched to/is a %User{} struct and nothing else.

The point of it is to identify bugs (by static program analysis) or force runtime errors/crashes so your program won't do anything harmful (hopefully).

Upvotes: 1

Related Questions