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?
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.