Code Example Template
Deep-Dive System Documentation
Conditional Expressions in Rust
In Rust, if is not a statement; it is an expression. This means that conditional blocks return values that can be assigned directly to variables.
Core Rules
- Type Concordance: If you assign the result of an
if/elseblock, both theifandelsebranches must evaluate to the exact same return type. - No Implicit Coercions: The condition must evaluate strictly to a
bool. Numeric zero or null checks are not allowed as implicit conditions.
let active_profile = if modifier_pressed {
"Photoshop"
} else {
"Default"
}; // both branches return &'static str
Performance Metrics
- Storage: Instantly optimized into native CPU jump signals (e.g.,
je,jneassembly codes). - Branch Prediction: Clean structure allows compiler to apply optimal branch weights automatically.
- Safety: Eliminates initialization bugs by forcing all branches to evaluate.
Quick Reference Guide
let val = if condition { 1 } else { 2 };