if let Expressions
The
if let expression
lets you execute different code depending on whether a value matches a pattern:
use std::time::Duration; fn sleep_for(secs: f32) { let result = Duration::try_from_secs_f32(secs); if let Ok(duration) = result { std::thread::sleep(duration); println!("slept for {duration:?}"); } } fn main() { sleep_for(-10.0); sleep_for(0.8); }
- Unlike
match,if letdoes not have to cover all branches. This can make it more concise thanmatch. - A common usage is handling
Somevalues when working withOption. - Unlike
match,if letdoes not support guard clauses for pattern matching. - With an
elseclause, this can be used as an expression.