2
votes

I am struggling to understand pattern matching in my specific case; I'm trying to get the values from params, which I think is a struct, in a Phoenix controller.

Typing params in iex results in

%{"edit" => "93213e66-a15e-11e6-8bc7-38c986312498",
  "job_slug" => "7759-tkhkjd-test"}

However, running the following command:

pry(7)> {edit, job_slug} = params

throws this error:

** (MatchError) no match of right hand side value: %{"edit" => "93213e66-a15e-11e6-8bc7-38c986312498", "job_slug" => "7759-tkhkjd-test"}
     (stdlib) :erl_eval.expr/3

How do I correctly pattern match against params?

2

2 Answers

7
votes

Your params is a Map but you are matching it against a Tuple. You should try this:

%{"edit" => edit, "job_slug" => job_slug} = params

From the Elixir Pattern Matching guide:

The match operator (=) is not only used to match against simple values, but it is also useful for destructuring more complex data types. [...] A pattern match will error in the case the sides can’t match [...] and also when comparing different types.

This means your LHS and RHS must be of the same type, and must match correctly to assign the variables on the left. In your case you had a Map on your right hand side, and a Tuple on your left hand side, which raised a MatchError.


Relevant Links:

0
votes

You need to match the struct, not just the inside bits:

%{"edit" => edit, "job_slug" => job_slug} = params