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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 24, 2023 (edit).