Understanding functions and arguments

Hi! I am a complete beginner in Elixir and Phoenix. I am trying to understand couple of things and I will be grateful for your help!

What is the meaning of this argument %{"id" => id}?
It is used in this function:

def show(conn, %{"id" => id}) do
user = Accounts.get_user(id)
render(conn, "show.html", user: user)


It’s called pattern matching. You expect an argument that is a map with an “id” key and assigns it’s value to id variable Pattern matching - The Elixir programming language

1 Like

Thank you for the reply!

I did read the link that you’ve given me before, however I still struggle to understand where it comes from. Is this argument in conn? That’s where it is looking for it?

Elixir allows you to pattern match on arguments, so you can say that this function expects the argument passed to it to have some shape defined by you. When you call the function it will execute only when the argument matches the expectation. In this case the second argument is params passed to the action by a router. Let’s say the call looks like this

FooController.show(conn, params)

If params is %{"id" => 1, "comment" => "Some Text"} it will execute your function. If it is for example %{"comment" => "Some Text"} elixir will look for another definition of show that actually can match on this value. If it doesn’t find any, elixir will raise an error.

You can redefine your function to be and it will have the same effect

def show(conn, params) do
  case params do
    %{"id" => id} ->
       user = Accounts.get_user(id)
       render(conn, "show.html", user: user)
    _ -> 
       raise MatchError

Or you can also take a look at Functions · Elixir School


Thank you so much, I think I get it now! This is the answer I hoped for! :slight_smile: