Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "<>" operator in an elixir function signature?

I see this function signature sometimes and can't find anything on it:

def handle("user:" <> id), do: Repo.get(User, id)

I am new to erlang/elixir so I assume this is some sort of pattern matching for user:1 and user:2, but I haven't seen any articles or information about this specifically in the Elixir guides.

What exactly is going on here?

like image 712
bschaeffer Avatar asked Jul 21 '16 14:07

bschaeffer


1 Answers

Yes, it's a pattern in this case. "user:" <> id will match any binary starting with user:, and assign the part of the string after user: to id.

iex(1)> "user:" <> id = "user:"
"user:"
iex(2)> id
""
iex(3)> "user:" <> id = "user:123"
"user:123"
iex(4)> id
"123"
iex(5)> "user:" <> id = "user"
** (MatchError) no match of right hand side value: "user"

Note that the same operator is also used to concatenate binaries when used as an expression:

iex(1)> id = "123"
"123"
iex(2)> "user:" <> id
"user:123"
like image 72
Dogbert Avatar answered Oct 29 '22 02:10

Dogbert