Using Guard Clauses
Guard Clauses: Adding Conditions to Your Matches
Welcome back. In the previous lesson, you used multiple function clauses to match different input shapes right in the function head. As a reminder, we also briefly used a guard to prevent dividing by zero. In this lesson, you will focus on guard clauses themselves — how to attach conditions to a clause so it runs only when certain checks (type, range, etc.) are true.
Guard Clauses in Action
Explanation:
- The module defines three clauses of the same function,
validate_age/1. Elixir tries them from top to bottom and picks the first one whose pattern matches and whose guard evaluates totrue. - First clause: applies only when
ageis an integer and between 0 and 17. It returns{:ok, "Minor"}. - Second clause: applies only when
ageis an integer and at least 18. It returns{:ok, "Adult"}. - Third clause: no guard, catches everything else — negative numbers, non-integers, etc. The parameter is named
_ageto signal it is intentionally ignored. It returns{:error, "Invalid age"}. - The three
IO.inspectcalls show:15->{:ok, "Minor"}25->{:ok, "Adult"}-5->{:error, "Invalid age"}(it fails the first guard due toage >= 0and fails the second guard due toage >= 18)
- Why guards? They let you keep your routing logic clean and declarative. You match the input shape in the head, then refine with boolean checks like
is_integer(age), comparisons, and logicaland. Note: Guards accept a limited, “guard-safe” set of operations — perfect for validation like this.
What’s Allowed in Guards
- Type checks:
is_atom/1,is_binary/1,is_bitstring/1,is_boolean/1,is_float/1,is_function/1,2,is_integer/1,is_list/1,is_map/1,is_nil/1,is_number/1,is_pid/1,is_port/1,is_reference/1,is_tuple/1 - Comparisons:
==,!=,===,!==,<,<=,>,>=, and theinoperator (with lists/ranges) - Arithmetic and numeric:
+,-,*,div/2,rem/2,abs/1 - Boolean operators:
and,or,not(see operator nuances below) - Size/access helpers:
byte_size/1,bit_size/1,tuple_size/1,map_size/1,elem/2,map_size/1
Not allowed:
- User-defined functions or most library calls (e.g.,
Enum.*,Map.*). For example,Map.has_key?/2,Enum.count/1,length/1,hd/1,tl/1, and the/operator (floating-point division) are not allowed in guards. - Operators
&&,||,!are not allowed in guards; useand,or,notinstead.
Important: Only use functions and operators that are explicitly documented as guard-safe in the Elixir documentation. Using non-guard-safe functions in guards will cause compilation errors. Always avoid non-guard-safe functions in guard expressions.
