if let
Combines a pattern match
and an if
statement, and allows for brief non-exhaustive matches to be performed.
if let Some(x) = option {
do_something(x);
}
This is equivalent to:
match option {
Some(x) => do_something(x),
_ => {},
}
These blocks can also have else
statements.
if let Some(x) = option {
do_something(x);
} else {
panic!("option was None");
}
This block is equivalent to:
match option {
Some(x) => do_something(x),
None => panic!("option was None"),
}
while let
Combines a pattern match and a while loop.
let mut cs = "Hello, world!".chars();
while let Some(x) = cs.next() {
print("{}+", x);
}
println!("");
This prints H+e+l+l+o+,+ +w+o+r+l+d+!+
.
It's equivalent to using a loop {}
and a match
statement:
let mut cs = "Hello, world!".chars();
loop {
match cs.next() {
Some(x) => print("{}+", x),
_ => break,
}
}
println!("");