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().
Tip We could use 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
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.
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.
fn main() {
let bird = 10;
// An if-else expression returns a value.
let value = if bird == 10 {
5
} else {
20
};
println!("{}", value);
}5
Performance note. In tests, a match statement can perform faster than an if-statement when compiled. Sometimes the benefit to using match is significant.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 24, 2023 (edit).