Rust – While let Statement
A Rust While let Statement in Rust is a special statement that basically refractors and allows us to view a clean code. While let statement was inspired by the if let statement in Rust.
Basically in an, if let statement, there is a pattern match and then the block of code gets executed.
if let Some(n) = option {
does_something(n);
}
This statement is equivalent to:
match option {
Some(x) => does_something(n),
_ => {},
}
While let is also similar to the above example.
In Rust, if we write a pattern match and loop, the expression looks like this:
Example 1:
Rust
fn main() { //gfg -> variable let mut gfg = "Printing w3wiki without using while let" .chars(); loop { match gfg.next() { Some(x) => print!( "{}" , x), _ => break , } } println!( "" ); } |
Output:
Now, using the while let statement in Rust. Using while let makes this code easier to read.
Example 2:
Rust
fn main() { //gfg is a variable let mut gfg = "Printing w3wiki using while let" .chars(); while let Some(x) = gfg.next() { //print is a statement that is used to print characters in one line print!( "{}" ,x); } println!( "\n" ); } |
Output:
Contact Us