1

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.

Vadim Sentiaev
  • 741
  • 4
  • 18
harleyqmc
  • 11
  • 1
  • 1
    In case you were wondering about the order, `%User{} = user` is the same as `user = %User{}` in patterns. – Dogbert May 10 '20 at 03:03
  • 1
    This **not an assignment** by any means. This is [pattern matching](https://elixir-lang.org/getting-started/pattern-matching.html). I would recommend starting with reading language guides instead of diving into frameworks. – Aleksei Matiushkin May 10 '20 at 05:03
  • This allows function overloading through pattern matching - see: https://stackoverflow.com/questions/23600513/elixir-function-overloading-with-different-arity – GavinBrelstaff May 10 '20 at 06:47

2 Answers2

1

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).

zwippie
  • 15,050
  • 3
  • 39
  • 54
1

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.

Everett
  • 8,746
  • 5
  • 35
  • 49