Guards are used as a complement to pattern matching. They allow for more complex checks. They can be used in some, but not all situations where pattern matching can be used, for example in function clauses or case clauses.
def empty?(list) when is_list(list) and length(list) == 0 do
true
end
Guards begin with the when
keyword, followed by a boolean expression.
Guard expressions are special functions which:
true
or false
values.A list of common guards are found in the Elixir documentation. They include:
You can define your own guard with defguard
.
According to Elixir's naming convention, guard names should start with is_
.
defmodule HTTP do
defguard is_success(code) when code >= 200 and code < 300
def handle_response(code) when is_success(code) do
:ok
end
end