if / else / if let
In Rust, if is an expression and can return a value. if let is a concise syntax for pattern matching on Option or Result values.
Syntax
// Standard if/else
if condition {
// body
} else if condition2 {
// body
} else {
// body
}
// Used as an expression (returns a value)
let variable = if condition { value1 } else { value2 };
// if let (pattern-match branching)
if let pattern = value {
// runs when pattern matches
} else {
// runs when pattern does not match
}
if / if let Comparison
| Syntax | Description |
|---|---|
| if condition | Standard conditional branch that evaluates a bool value. |
| else if condition | Chains multiple conditions together. |
| let x = if ... { } else { } | Uses if as an expression to assign a value to a variable. Each branch must return the same type. |
| if let Some(x) = opt | Runs only when the Option is Some. More concise than match for a single pattern. |
| if let Ok(x) = result | Runs only when the Result is Ok. |
Sample Code
fn classify(n: i32) -> &'static str {
if n > 0 {
"positive"
} else if n < 0 {
"negative"
} else {
"zero"
}
}
fn main() {
// Basic if/else
let score = 75;
let grade = if score >= 80 {
"A"
} else if score >= 60 {
"B"
} else {
"C"
};
println!("Grade: {}", grade); // Prints "B"
// Handle an Option with if let
let some_value: Option<i32> = Some(42);
if let Some(v) = some_value {
println!("Value is {}", v); // Prints "42"
} else {
println!("No value");
}
// Handle a Result with if let
let result: Result<i32, &str> = Ok(100);
if let Ok(n) = result {
println!("Success: {}", n);
}
println!("{}", classify(5));
println!("{}", classify(-3));
}
Notes
Because if in Rust is an expression rather than a statement, you can use it in place of a ternary operator. Each branch must return the same type; a type mismatch causes a compile error.
if let is useful when you only need to handle a single pattern from an Option or Result. When you need to handle multiple patterns, match is clearer and more readable. See match / Pattern Matching for details.
If you find any errors or copyright issues, please contact us.