1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-04 21:58:46 +02:00

Miscellaneous minor improvements (#2370)

This commit is contained in:
Nicole L
2024-09-20 14:19:53 -07:00
committed by GitHub
parent aeb643f380
commit 2f9babd098
11 changed files with 57 additions and 37 deletions

View File

@ -47,12 +47,5 @@ arm, `half` is bound to the value inside the `Ok` variant. In the second arm,
matched.
- Demonstrate what happens when the search is inexhaustive. Note the advantage
the Rust compiler provides by confirming when all cases are handled.
- Save the result of `divide_in_two` in the `result` variable and `match` it in
a loop. That won't compile because `msg` is consumed when matched. To fix it,
match `&result` instead of `result`. That will make `msg` a reference so it
won't be consumed. This
["match ergonomics"](https://rust-lang.github.io/rfcs/2005-match-ergonomics.html)
appeared in Rust 2018. If you want to support older Rust, replace `msg` with
`ref msg` in the pattern.
</details>

View File

@ -44,11 +44,11 @@ fn eval(e: Expression) -> Result<i64, String> {
Expression::Op { op, left, right } => {
let left = match eval(*left) {
Ok(v) => v,
e @ Err(_) => return e,
Err(e) => return Err(e),
};
let right = match eval(*right) {
Ok(v) => v,
e @ Err(_) => return e,
Err(e) => return Err(e),
};
Ok(match op {
Operation::Add => left + right,

View File

@ -56,4 +56,24 @@ Key Points:
- The condition defined in the guard applies to every expression in a pattern
with an `|`.
# More To Explore
- Another piece of pattern syntax you can show students is the `@` syntax which
binds a part of a pattern to a variable. For example:
```rust
let opt = Some(123);
match opt {
outer @ Some(inner) => {
println!("outer: {outer:?}, inner: {inner}");
}
None => {}
}
```
In this example `inner` has the value 123 which it pulled from the `Option`
via destructuring, `outer` captures the entire `Some(inner)` expression, so it
contains the full `Option::Some(123)`. This is rarely used but can be useful
in more complex patterns.
</details>