add one exercise in patterns.md

This commit is contained in:
sunface 2022-03-11 15:45:03 +08:00
parent 7bc4cf757b
commit 553f7b1648
3 changed files with 43 additions and 0 deletions

View File

@ -85,4 +85,17 @@ fn main() {
}
}
}
```
6.
```rust
fn main() {
let mut v = String::from("hello,");
let r = &mut v;
match r {
// The type of value is &mut String
value => value.push_str(" world!")
}
}
```

View File

@ -101,4 +101,19 @@ fn main() {
}
```
6. 🌟🌟 Using pattern `&mut V` to match a mutable reference needs you to be very careful due to `V` being a value after matching
```rust,editable
// FIX the error with least changing
// DON'T remove any code line
fn main() {
let mut v = String::from("hello,");
let r = &mut v;
match r {
&mut value => value.push_str(" world!")
}
}
````
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it

View File

@ -97,4 +97,19 @@ fn main() {
}
```
6. 🌟🌟 使用模式 `&mut V` 去匹配一个可变引用时,你需要格外小心,因为匹配出来的 `V` 是一个值,而不是可变引用
```rust,editable
// 修复错误,尽量少地修改代码
// 不要移除任何代码行
fn main() {
let mut v = String::from("hello,");
let r = &mut v;
match r {
&mut value => value.push_str(" world!")
}
}
````
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)