doc.rust-lang.org
Destructuring
A match block can destructure items in a variety of ways.
• Destructuring Tuples
• Destructuring Arrays and Slices
• Destructuring Enums
• Destructuring Pointers
• Destructuring Structures
See also:
The Rust Reference for Destructuring
Rust by Example
Book
2024-01-01
~1 min read
github.com
...r##"
> An "or" pattern was used where the variable bindings are not consistently bound
> across patterns.
>
> Example of erroneous code:
>
> ```compile_fail
> let x = (0, 2);
> match x {
> (0, ref y) | (y, 0) => { /* use y */} // error: variable `y` is bound with
> // different mode in pattern #2
> // than in pattern #1...
RFC 1567
RFC
2016-01-04
~3 min read
quickwit.io
...All documents matching this query must also match the query tenant_id=57.
Quickwit will only search into the splits with 57 within their tenant_id values.Finally, we entirely revamped our indexing pipeline.By default, it now emits splits every sixty seconds.
The pipeline also transparently takes care of...
Project/Tooling Updates
2022-01-19
~6 min read
dev.to
...fn normalize_next_url(next: &str, base: &str) -> String {
let path_and_query = match next.find("://") {
Some(scheme_end) => {
let after_scheme = &next[scheme_end + 3..];
match after_scheme.find('/') {
Some(path_start) => &after_scheme[path_start..],
None => "/",
}
}
None => next,
};
format!("{}{}", base, path_and_query)
}
Enter fullscreen mode
Exit fullscreen...
Rust Walkthroughs
2026-07-22
~3 min read
github.com
...F) -> U {
match self {
Some(t) => f(t),
None => Default::default(),
}
}
}
```
The following implementation would get added to `core::result::Result`:
```rust
impl<T, E> Result<T, E> {
pub fn map_or_default<U: Default, F: FnOnce(T) -> U>(self, f: F) -> U {
match self {
Ok(t) => f(t),
Err...
RFC 3148
RFC
2021-07-14
~1 min read
joelmccracken.github.io
...use std::fs::File;
fn log_something(filename, string) {
let mut f = try!(File::create(filename));
try!(f.write_all(string));
}
fn main() {
match log_something("log.txt", "ITS ALIVE!!!") {
Ok(..) => println!("File created!"),
Err(..) => println!("Error: could not create file.")
}
}
=>
$ cargo run
Compiling simple-log v0.1.0 (file...
Notable Links
2015-06-07
~6 min read
aloso.github.io
...impl<It> Node<It> { fn traverse(&self) { match self { Node::Leaf(_) => {} Node::Children(children) => { for node in children { node.traverse(); } } } }}
If we want to do something with each item, we can pass a closure to the function:
impl<It> Node<It> { fn traverse(&self, f: impl Fn(&It)) { match self...
Rust Walkthroughs
2021-03-10
~7 min read
pksunkara.com
...Rails
match 'orgs', to: 'orgs#create', via: [:post, :put]
Django
path('orgs', views.orgs.create),@require_http_methods(["POST", "PUT"])
def create(request):
pass
Laravel
<?php
Route::match(['post', 'put'], 'orgs', 'OrgsController@create');
Actix
app.service(
resource("orgs")
.route(post().to(orgs::create))
.route(put().to(orgs::create))
);
Cons
This...
News & Blog Posts
2020-05-19
~8 min read
erickt.github.io
...Token) -> Result<Point, E> {
try!(state.expect_struct_start(token, "Point"));
let mut x = None;
let mut y = None;
loop {
let idx = match try!(state.expect_struct_field_or_end(&["x", "y"])) {
Some(idx) => idx,
None => { break ; }
};
match idx {
Some(0us) => { x = Some(try!(state.expect_struct_value())); }
Some(1us...
Project Updates
2015-02-16
~4 min read
kerkour.com
...For that, we use the Host extractor and pattern matching:
#[tokio::main]
async fn main() {
// ...
let app = Router::new()
.route(
"/*path",
any(|Host(hostname): Host, request: Request<Body>| async move {
match hostname.as_str() {
"api.mydomain.com" => api_router.oneshot(request).await,
_ => website_router.oneshot(request).await,
}
}),
)
.layer(Extension(state...
Rust Walkthroughs
2022-04-20
~1 min read
www.goldsborough.me
...Below is the code for the match arm handling GET requests. It’s slightly more
logic than before:
(&Get, "/") => {
let time_range = match request.query() {
Some(query) => parse_query(query),
None => Ok(TimeRange {
before: None,
after: None,
}),
};
let response = match time_range {
Ok(time_range) => make_get_response(query_db...
News & Blog Posts
2018-03-06
~23 min read
doc.rust-lang.org
...In the search_case_insensitive function we’re about to add, the query "rUsT" should match the line containing "Rust:" with a capital R and match the line "Trust me." even though both have different casing from the query. This is our failing test, and it will fail to compile...
The Rust Programming Language
Book
2024-02-01
~6 min read
fnordig.de
...extern crate hyper;
extern crate hubcaps;
use std::{env, process};
use hyper::Client;
use hubcaps::{Github, ReleaseOptions};
fn main() {
let token = match env::var("GITHUB_TOKEN").ok() {
Some(token) => token,
_ => {
println!("example missing GITHUB_TOKEN");
process::exit(1);
}
};
let client = Client::new();
let github = Github::new("hubcaps/0.1.1...
News & Blog Posts
2016-02-29
~1 min read
mdguerrero.com
...fn string_csv_contains(args: &HashMap<String, Value>) -> Result<Value> {
let mut out = false;
let check_str = match args.get("check_str") {
Some(val) => match tera::from_value::<String>(val.clone()) {
Ok(v) => v,
Err(_) => "".to_string(),
},
None => "".to_string(),
};
let csv = match args.get("csv") {
Some(val) => match tera...
Miscellaneous
2022-02-02
~12 min read
benkonz.github.io
...Just read every character and match the character with a command. If the character isn’t a command, just skip it and move to the next character.
Commands
Character
Meaning
>
increment data pointer
<
decrement data pointer
+
increment the byte at the data pointer
-
decrement the byte at the data pointer...
Learn More Rust
2020-08-11
~10 min read
seanmonstar.com
...However, we couldn’t add it in 0.1 due to an unexpected compiler behavior that allowed exhaustive matching on the Version constants even though the internal enum wasn’t exposed. This time, we’ve made sure to prevent exhaustive matches, so we can add new versions in the future...
News & Blog Posts
2019-12-03
~1 min read
tuckersiemens.com
...Even so, Rust's (appreciated)
insistence on exhaustively matching patterns would make us write code like
this.
match packet(&data)? {
Packet::Data => handle_data(),
Packet::Ack => handle_ack(),
Packet::Error => handle_error(),
_ => unreachable!("Didn't we already handle this?"),
}
Also, you might be tempted to use unreachable! for such code...
Observations/Thoughts
2023-01-04
~21 min read
hackeryarn.com
...Evaluate if you need a macro
Design the simplest possible invocation first (determine what your DSL looks like)
Try to implement a match arms and adjust the invocation as needed
Work one match arm at a time
Write sub macros where possible
Some of these steps might not mean much...
Rust Walkthroughs
2025-08-20
~6 min read
blog.dend.ro
...Vec<Matching>,
}
#[derive(Deserialize, Debug)]
pub struct Matching {
pub geometry: String,
}
Then our client:pub struct OsrmClient {
client: Client,
base_url: String,
}
impl OsrmClient {
pub fn new(base_url: String) -> Self {
let client = Client::new();
Self { client, base_url }
}
pub fn match_map(
&self,
profile: &str,
points: &[Point],
) -> Result<MultiLineString...
Rust Walkthroughs
2022-01-19
~9 min read
xuanwo.io
...start_match = start_pattern.match(line)
if start_match:
timestamp, file_name, data_size = start_match.groups()
starts[file_name] = (datetime.fromisoformat(timestamp), int(data_size))
end_match = end_pattern.match(line)
if end_match:
timestamp, file_name, _ = end_match.groups()
ends[file_name] = datetime.fromisoformat(timestamp)
read_times = []
for...
Observations/Thoughts
2024-01-24
~11 min read