update match-iflet.md

This commit is contained in:
sunface
2022-03-01 19:44:47 +08:00
parent 726ef682cb
commit bc36dd3a01
2 changed files with 274 additions and 4 deletions

View File

@ -32,8 +32,8 @@ fn main() {
// fill the blank with an match expression:
//
// boolean = true, binary = 1
// boolean = false, binary = 0
// boolean = true => binary = 1
// boolean = false => binary = 0
let binary = __;
assert_eq!(binary, 1);
@ -116,4 +116,80 @@ fn main() {
}
```
### if let
### if let
For some cases, when matching enums, `match` is too heavy, we can use `if let` instead.
🌟
```rust,editable
fn main() {
let o = Some(7);
// remove the whole `match` block, using `if let` instead
match o {
Some(i) => {
println!("This is a really long string and `{:?}`", i);
}
_ => {}
};
}
```
🌟🌟
```rust,editable
// fill in the blank
enum Foo {
Bar(u8)
}
fn main() {
let a = Foo::Bar(1);
__ {
println!("foobar holds the value: {}", i);
}
}
```
🌟🌟
```rust,editable
enum Foo {
Bar,
Baz,
Qux(u32)
}
fn main() {
let a = Foo::Qux(10);
// remove the codes below, using `match` instead
if let Foo::Bar = a {
println!("matches foo::bar")
} else if let Foo::Baz = a {
println!("matches foo::baz")
} else {
println!("matches others")
}
}
```
### Shadowing
🌟🌟
```rust,editable
// fix the errors in-place
fn main() {
let age = Some(30);
if let Some(age) = age { // create a new variable with the same name as previous `age`
assert_eq!(age, Some(30));
} // the new variable `age` goes out of scope here
match age {
// match can also introduce a new shadowed variable
Some(age) => println!("age is a new variable, it's value is {}",age),
_ => ()
}
}
```