while let Loop šÆWelcome to our Rust tutorial series! Today, we'll dive into the while let loop - a unique feature that combines the power of pattern matching and loops. Let's get started!
while let šThe while let loop is a looping construct that lets you iterate over a collection until a specific condition is met. It's particularly useful when dealing with iterators or other types that implement the Iterate trait.
Let's consider an example where we want to find the first even number in a vector:
let numbers = vec![1, 3, 4, 5, 7, 8];
let mut index = 0;
while let Some(number) = numbers.get(index) {
if number % 2 == 0 {
println!("Found even number: {}", number);
break;
}
index += 1;
}In this example, we have a vector numbers containing several integers. We use the get method to get the element at the current index, and while let to pattern match the Option returned by get. The loop continues as long as the value is Some, and breaks when we find an even number.
š” Pro Tip: Notice how we use the break statement to exit the loop once we've found the even number. This is a common pattern when using while let.
while let Examples š”Now that you have a basic understanding of while let, let's dive into some more advanced examples.
Consider the following example where we iterate over a string and count the number of vowels:
let text = "Hello World!";
let mut vowel_count = 0;
let vowels = vec!['a', 'e', 'i', 'o', 'u'];
let chars: Vec<char> = text.chars().collect();
while let Some(c) = chars.get(0) {
if vowels.contains(c) {
vowel_count += 1;
}
chars.drain(0..1);
}
println!("Number of vowels: {}", vowel_count);In this example, we create a vector chars containing the characters of the string text. We use while let to pattern match the characters, and if the character is a vowel, we increment the vowel_count. After processing each character, we remove it from the chars vector using the drain method.
That's all for today! We've covered the basics and some advanced examples of the while let loop in Rust. In the next lesson, we'll explore more Rust concepts to help you become a proficient Rust programmer! š
Stay tuned and happy coding! š»š