Rust functions often return Options and Results. If we call unwrap()
on these return values, our Rust code can become ugly and hard to read.
With if let, we can omit the unwrap()
call—the call is added automatically by the Rust compiler. We use the syntax if let Some, and if let Ok.
Consider this Rust program. It first calls find()
, which returns an Option
. We can let Some()
directly in an if
-statement to capture the inner result without calling unwrap()
.
Some()
of the first if
-statement, we have a named variable "m" that is assigned to the result of unwrap()
.open()
which returns a Result
. We use Ok()
to get the result of unwrap()
if the call succeeded.unwrap()
to test the results of these functions. But the if-let
syntax is clearer and easier to review.use std::io::*; use std::fs::*; fn main() { let value = "orange cat"; // Use if-let to unwrap an option without calling unwrap. if let Some(m) = value.find("cat") { println!("IF LET SOME = {}", m); } // Use if-let to unwrap a result without calling unwrap. if let Ok(f) = File::open("/Users/sam/example.txt") { let reader = BufReader::new(f); let mut count = 0; for _ in reader.lines() { count += 1; } println!("IF LET OK = {}", count); } }IF LET SOME = 7 IF LET OK = 581
For strings in Rust, we cannot test letter individually in if
-statements. We can use a range and compare the result to a str
.
if
-statements. We also use else if, else, and a boolean operator to test values.If
-statements in Rust work similarly as they do in other languages. Most code can be translated line-by-line.fn main() { let data = "bird, frog"; // Test with if. if &data[0..1] == "b" { println!("BIRD FOUND"); } let data = "Carrot"; // Test with if, else if, else. if &data[0..1] == "x" { println!("X FOUND"); } else if &data[0..2] == "ca" || &data[0..2] == "Ca" { println!("CARROT FOUND"); } else { println!("NOTHING"); } }BIRD FOUND CARROT FOUND
In Rust, if-else
is an expression—it returns a value. We can assign to the result of an if-else
expression and store the result in a local variable.
fn main() { let bird = 10; // An if-else expression returns a value. let value = if bird == 10 { 5 } else { 20 }; println!("{}", value); }5
In tests, a match statement can perform faster than an if
-statement when compiled. Sometimes the benefit to using match is significant.
If
-statements in Rust work about the same as if
-statements in other programming languages. A key thing to know is how to use if-let
with Some or Ok to unwrap()
results inline.