Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between => and : in an Elixir map?

In the Phoenix framework

def show(conn, %{"id" => id}) do
  json conn, Repo.get(User, id)
end

matches fine, but using the : notation does not pattern match

def show(conn, %{"id": id}) do
  json conn, Repo.get(User, id)
end

when I call the following code from a test

conn
|> get(user_path(conn, :show, user.id))
|> json_response(200)
like image 212
Joris Kok Avatar asked Sep 11 '25 13:09

Joris Kok


2 Answers

%{key: value} is a short-hand for Atom keys, not String keys. Let's clear up a few things:

:"a" == "a"
# => false

:"a" == :a
# => true

%{:a => 1} == %{"a": 1}
# => true

So when you write %{"id": id}, it means: %{id: id} which is not %{"id" => id}, and since your params map does not have an :id key, it does not match.


As a side note, I actually wrote a Plug to use atom keys in Phoenix controllers to keep params matching short and sweet.

like image 129
Sheharyar Avatar answered Sep 13 '25 05:09

Sheharyar


When you use : the key is an atom. When you use => the key is whatever the type actually is. %{key: val} is actually just sugar for %{:key => val}.

like image 31
Justin Wood Avatar answered Sep 13 '25 05:09

Justin Wood