mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-25 21:49:41 +00:00
update match-iflet.md
This commit is contained in:
@ -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),
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user