Home
Search
Rust if let Some, Ok ExamplesUse if-statements with let Some and let Ok to avoid calling unwrap on an Option or Result. Review if-statement syntax.
If let. 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.
match
Example. 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().
find, rfind
Some In the Some() of the first if-statement, we have a named variable "m" that is assigned to the result of unwrap().
Ok In the second part, we call File open() which returns a Result. We use Ok() to get the result of unwrap() if the call succeeded.
File
Tip We could use unwrap() to test the results of these functions. But the if-let syntax is clearer and easier to review.
Rust program that uses if let Some, let Ok
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
Test strings. For strings in Rust, we cannot test letter individually in if-statements. We can use a range and compare the result to a str.
Info Here we test the first chars of strings in if-statements. We also use else if, else, and a boolean operator to test values.
Tip If-statements in Rust work similarly as they do in other languages. Most code can be translated line-by-line.
Rust program that uses if to test strings
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
Assign if. 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.
Rust program that assigns to if-else expression
fn main() { let bird = 10; // An if-else expression returns a value. let value = if bird == 10 { 5 } else { 20 }; println!("{}", value); }
5
A summary. 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.
Home
© 2007-2022 sam allen.
see site info on the changelog.