Skip to main content
In Rust, if is a control flow construct that evaluates a boolean condition to determine execution paths. Crucially, if in Rust is an expression, not a statement. This means it evaluates to a value and can be bound to variables, passed to functions, or returned from blocks.

Syntax and Structural Rules

The syntax requires the if keyword followed by a condition and a block of code.
Rust enforces strict structural rules for if expressions:
  1. No Parentheses: Parentheses () around the condition are syntactically valid but idiomatic Rust omits them. The compiler will issue a warning if they are included unnecessarily.
  2. Mandatory Braces: Curly braces {} are strictly required around the execution block, even if the block contains only a single expression.
  3. Strict Boolean Typing: The condition must evaluate to a strict bool type. Rust does not perform implicit type coercion (truthiness). Passing an integer, string, or pointer directly as a condition results in a compile-time type error.

Expression Semantics and Type Matching

Because if is an expression, it yields the value of the final expression evaluated within the executed block. When an if expression is used to assign a value, the compiler enforces strict type uniformity across all branches.
If the branches return disparate types, the compiler will throw a mismatched types error.

The Unit Type () in if Expressions

If an if expression does not include an else branch, it implicitly evaluates to the unit type (). Consequently, if an if block without an else evaluates to a type other than (), it will trigger a compile-time error.

if let Pattern Matching

Rust provides a specialized variant called if let, which combines if with pattern matching. It is syntactic sugar for a match expression that only cares about a single pattern, ignoring all others.
The if let construct adheres to the same expression semantics and type-matching rules as a standard if expression.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More