33
loading...
This website collects cookies to deliver better user experience
def can_access?(%User{paid_user: true}), do: true
user with level > 25
to access.guard
shines, it is complement for Pattern Matchingdef can_access?(%User{level: level}) when level > 25, do: true
Guard is a complement to your pattern matching to do more complex check.
Guard expression is invoke after pattern mattching
In many cases, Guard
and Pattern matching
can produce the same result, so use which you like.
# sum on empty list
# pattern matching
def sum_list([] = _input), do: 0
# guard
def sum_list(input) when input == [], do: 0
def sum(a, b) when is_integer(a) and is_integer(b) do
a + b
end
def string_length(string) when not is_nil(string) do
# your code
end
def can_edit?(%User{role: role}) when role in ["admin", "moderator"] do
true
end
case
block
case value do
x when is_binary(x) -> String.to_integer(x)
x when is_integer(x) -> x
_ -> raise "Invalid value"
end
with
block
with user when not is_nil(user) <- find_user(id) do
# your code block
end
function
clause as our example aboveguard
and combination of them work in guard expression.==
, !=
, ===
, !==
, >
, >=
, <
, <=
)and
, or
, not
). Note &&
, ||
, and !
sibling operators are not allowed as they're not strictly boolean - meaning they don't require arguments to be booleans+
, -
, +
, -
, *
, /
)in
and not in
operators (as long as the right-hand side is a list or a range)is_list/1
, is_number/1
, etc.)abs/1
, map_size/1
, etc.)defguard/1
and defguardp/1
. But you should only define your own guard if you have a really really reasonable reason to do so.33