Pattern matching is a rare language feature that Elixir includes. It’s quite similar to de-structuring that you’d find in other languages, but with some other nuances. I’ll focus on its similarities to de-structuring for now.
defmodule Response do
defstruct body: ""
end
defmodule ErrorResponse do
defstruct body: "", status: 0
end
defmodule Api do
def call(endpoint) when endpoint == "a" do
{%Response{body: "Hello"}, nil}
end
def call(endpoint) when endpoint == "b" do
{nil, %ErrorResponse{body: ~s({errors: [{message: "An error occured", status: 503}]}), status: 503}}
end
end
defmodule Main do
def main do
{:ok, integer} = {:ok, 13} # makes an assertion that the second item in the tuple exists and assigns that value to integer, otherwise throws an error
IO.inspect(integer)
# 13
{response, err} = Api.call("a") # this might not be idiomatic, but gets the point across
if response do
IO.inspect(response, label: "response from a")
# response from a: %Response{body: "Hello"}
end
if err do
IO.inspect(err, label: "err from a")
end
{response, err} = Api.call("b")
if response do
IO.inspect(response, label: "response from b")
end
if err do
IO.inspect(err, label: "err from b")
# err from b: %ErrorResponse{
body: "{errors: [{message: \"An error occured\", status: 503}]}",
status: 503
}
end
end
end
Main.main()