Coding/Learn/rust/control flow and branches
Rust Foundational Course
01.Introduction to Rust & Memory Safety
02.Formatting, Comments & Macros (println!)
03.Variables, Mutability & Shadowing
04.Scalar & Compound Types (Integers, Floats, Tuples, Arrays)
05.Functions, Parameters & Return Expressions
06.Conditionals & If as an Expression
07.Ownership Rules & Move Semantics
08.References & Borrowing (&T)
09.Mutable References (&mut) & Aliasing XOR Mutability
10.Slices & String Types (&str vs String)
11.Loops in Rust (loop, while, for)
12.Pattern Matching with match Expressions
13.Structs, Associated Functions & Methods (impl)
14.Enums & the Option<T> Type (No Null!)
15.Concise Pattern Matching (if let & let else)
16.Vectors & Growable Collections (Vec<T>)
17.Error Handling with Result<T, E> & the ? Operator
18.Traits, Shared Behavior & Generics
19.Closures & Functional Iterators (map, filter, collect)
20.Capstone: High-Performance In-Memory Log Telemetry Engine
Course Certificate0%

Complete all lessons to earn

LearnConditionals & If as an Expression
6 / 20 0%
Lesson 06 of 20
5 mins read

Conditionals & If as an Expression

PreviousNext Lesson
In Plain English

In Rust, if conditions must be explicit booleans (no automatic truthy/falsy coercion). Because if is an expression, you can assign its result directly to a let binding: let x = if cond { 5 } else { 10 };.

The Mental Model

"Because if is an expression in Rust, it acts like an automated vending chute: pick button A and it dispenses item 1; pick button B and it dispenses item 2 directly into your basket."

Deep Dive: How It Works

Strict Booleans: Conditions must evaluate strictly to bool (e.g. if count != 0, not if count).

If in let Bindings: Both if and else arms must evaluate to the exact same type.

No Parentheses Required: Rust does not require parentheses around if conditions.

Syntax Blueprint

let status = if score >= 90 { "Pass" } else { "Review" };

Assigns the resulting branch expression directly into the status variable binding.

PointCore Rules to Remember

Point star
if Expression: Can be used as a statement or assigned directly to variables.
Point star
Type Consistency: All arms in an if expression assignment must return the same type.
Point star
No Coercion: No numbers or pointers as implicit booleans.

Common Beginner Traps & How to Fix Them

Mistake:Returning different types from if and else arms in a let binding.

Why it happens: let x = if true { 5 } else { "five" }; fails because types must match at compile time.

How to fix: Ensure all branches evaluate to the exact same type.

Pro Tip: Use if expressions instead of declaring a let mut variable and assigning inside if blocks.

Live Interactive Example

Hit Run Code to see it live
Branching and Expression Assignments
Rust 1.78 / rustc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: The if expression evaluates the auth_level and binds "Administrator" to access_role.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Evaluate system load with if expression

  • PointGiven let load_percent = 85;
  • PointUse an if expression to set let status = if load_percent > 80 { "HIGH" } else { "NORMAL" };
  • PointPrint "System Status: HIGH".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates