You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-16 22:27:34 +02:00
Publish Comprehensive Rust 🦀
This commit is contained in:
7
src/pattern-matching/destructuring-arrays.md
Normal file
7
src/pattern-matching/destructuring-arrays.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Destructuring Arrays
|
||||
|
||||
You can destructure arrays, tuples, and slices by matching on their elements:
|
||||
|
||||
```rust,editable
|
||||
{{#include ../../third_party/rust-by-example/destructuring-arrays.rs}}
|
||||
```
|
31
src/pattern-matching/destructuring-enums.md
Normal file
31
src/pattern-matching/destructuring-enums.md
Normal file
@ -0,0 +1,31 @@
|
||||
# Destructuring Enums
|
||||
|
||||
Patterns can also be used to bind variables to parts of your values. This is how
|
||||
you inspect the structure of your types. Let us start with a simple `enum` type:
|
||||
|
||||
```rust,editable
|
||||
enum Result {
|
||||
Ok(i32),
|
||||
Err(String),
|
||||
}
|
||||
|
||||
fn divide_in_two(n: i32) -> Result {
|
||||
if n % 2 == 0 {
|
||||
Result::Ok(n / 2)
|
||||
} else {
|
||||
Result::Err(format!("cannot divide {} into two equal parts", n))
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let n = 100;
|
||||
match divide_in_two(n) {
|
||||
Result::Ok(half) => println!("{n} divided in two is {half}"),
|
||||
Result::Err(msg) => println!("sorry, an error happened: {msg}"),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here we have used the arms to _destructure_ the `Result` value. In the first
|
||||
arm, `half` is bound to the value inside the `Ok` variant. In the second arm,
|
||||
`msg` is bound to the error message.
|
7
src/pattern-matching/destructuring-structs.md
Normal file
7
src/pattern-matching/destructuring-structs.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Destructuring Structs
|
||||
|
||||
You can also destructure `structs`:
|
||||
|
||||
```rust,editable
|
||||
{{#include ../../third_party/rust-by-example/destructuring-structs.rs}}
|
||||
```
|
8
src/pattern-matching/match-guards.md
Normal file
8
src/pattern-matching/match-guards.md
Normal file
@ -0,0 +1,8 @@
|
||||
# Match Guards
|
||||
|
||||
When matching, you can add a _guard_ to a pattern. This is an arbitrary Boolean
|
||||
expression which will be executed if the pattern matches:
|
||||
|
||||
```rust,editable
|
||||
{{#include ../../third_party/rust-by-example/match-guards.rs}}
|
||||
```
|
Reference in New Issue
Block a user