1
0
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:
Martin Geisler
2022-12-21 16:36:30 +01:00
commit c212a473ba
252 changed files with 8047 additions and 0 deletions

View 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}}
```

View 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.

View File

@ -0,0 +1,7 @@
# Destructuring Structs
You can also destructure `structs`:
```rust,editable
{{#include ../../third_party/rust-by-example/destructuring-structs.rs}}
```

View 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}}
```