saghm.github.io
...2, ..Default::default() };
Pattern match guards
Sometimes when pattern matching, the cases you want to handle
don’t map exactly to the patterns of the data you’re matching
on. For instance, you might write some code like this:
fn divide_opt(x: Option<i32>, y: Option<i32>) -> Option<i32...
News & Blog Posts
2019-04-02
~3 min read
doc.rust-lang.org
...f64) -> f64 {
// This is a three level match pyramid!
match checked::div(x, y) {
Err(why) => panic!("{:?}", why),
Ok(ratio) => match checked::ln(ratio) {
Err(why) => panic!("{:?}", why),
Ok(ln) => match checked::sqrt(ln) {
Err(why) => panic!("{:?}", why),
Ok(sqrt) => sqrt,
},
},
}
}
fn main() {
// Will this fail?
println!("{}", op(1.0...
Rust by Example
Book
2024-01-01
~1 min read
doc.rust-lang.org
tuples
Tuples can be destructured in a match as follows:
fn main() {
let triple = (0, -2, 3);
// TODO ^ Try different values for `triple`
println!("Tell me about {:?}", triple);
// Match can be used to destructure a tuple
match triple {
// Destructure the second and third elements
(0, y, z) => println!("First is...
Rust by Example
Book
2024-01-01
~1 min read
erickt.github.io
...Consider what happens
with matches. Consider:
1
2
3
4
match ... {
x => { ... }
y => { ... }
}
Is x or y a variable, or a variant? There’s no way to know unless you
perform name resolution, otherwise known as the resolve pass in the compiler.
Unfortunately though, there’s no way for Stateful...
News & Blog Posts
2016-02-08
~10 min read
doc.rust-lang.org
...let role = Student;
match stage {
// Note the lack of scoping because of the explicit `use` above.
Beginner => println!("Beginners are starting their learning journey!"),
Advanced => println!("Advanced learners are mastering their subjects..."),
}
match role {
// Note again the lack of scoping.
Student => println!("Students are acquiring knowledge!"),
Teacher => println!("Teachers are...
Rust by Example
Book
2024-01-01
~1 min read
smallcultfollowing.com
...The innermost expression that encloses both of these
expressions is the match itself (as depicted above), and hence the
borrow is considered to extend until the end of the
match. Unfortunately, the match encloses not only the Some branch,
but also the None branch, and hence when we go to...
News & Blog Posts
2016-05-09
~9 min read
rustc-dev-guide.rust-lang.org
...This means that matching on TyKind can easily be incorrect.
We handle normalization in two different ways. When proving Trait goals when normalizing associated types, we separately assemble candidates depending on whether they structurally match the self type. Candidates which match on the self type are handled in EvalCtxt::assemble...
Guide to Rustc Development
Book
2024-01-01
~2 min read
doc.rust-lang.org
...fn main() {
match a {
_ =>
// comment with =>
{
println!("A")
}
}
}
Style edition 2024:
fn main() {
match a {
_ =>
// comment with =>
{
println!("A")
}
}
}
Multiple inner attributes in a match expression indented incorrectly
Multiple inner attributes in a match expression were being indented incorrectly.
Style edition 2021:
pub fn main() {
match a {
#![attr1]
#![attr2]
_ => None...
The Rust Edition Guide
Book
2024-01-01
~7 min read
niedzejkob.p4.team
...non-exhaustive patterns: `(Some(_), Some(_))` not covered
--> example.rs:4:11
|
4 | match (old_thing, new_thing) {
| ^^^^^^^^^^^^^^^^^^^^^^ pattern `(Some(_), Some(_))` not covered
|
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
= note: the matched value is of type `(Option<Thing>, Option<Thing...
Observations/Thoughts
2021-07-21
~8 min read
rust-analyzer.github.io
#10519 (first contribution) set toolinfo in LSIF export.
#10522 (first contribution) fix serialization of SignatureHelp response.
#10534 (first contribution) improve logo rendering on dark backgrounds.
#10538 (first contribution) make brace matching prefer the one to the right of the cursor.
#10542 (first contribution) use workspace cargo to fetch rust-src...
Project/Tooling Updates
2021-10-20
~1 min read
mrtact.medium.com
...The clunkiness of having to match everything against a Result, only to then re-wrap each output in the correct variant, completely obscures the beauty of that match expression. I mean, seriously, look at it! Not blowing my own horn — I didn’t have to be all that smart to...
Rust Walkthroughs
2021-01-20
~3 min read
doc.rust-lang.org
...Condition operands must be either an [Expression] with a boolean type or a conditional let match.
If all of the condition operands evaluate to true and all of the let patterns successfully match their scrutinees, the consequent block is executed and any subsequent else if or else block is skipped...
The Rust Reference
Book
2024-01-01
~4 min read
www.jacobelder.com
← Back to all posts
One of the things I really like about Rust is its match expressions. Plenty of other languages like Ruby, Python, and Haskell have similar features, but it’s painfully absent in popular languages like JavaScript. There, we have only switch...case. That statement is not exhaustive...
Rust Walkthroughs
2024-02-28
~7 min read
kerkour.com
...u64) {
let timeout = Duration::from_secs(timeout);
let socket_address = SocketAddr::new(target.clone(), port);
match tokio::time::timeout(timeout, TcpStream::connect(&socket_address)).await {
Ok(Ok(_)) => println!("{}", port),
_ => {}
}
}
Extreme concurrency
If you are a recurrent reader of this blog you should have guessed the perfect concurrency primitive for the...
Rust Walkthroughs
2021-08-18
~3 min read
blog.pnkfx.org
...use of moved value: `matches`
--> src/lib.rs:11:36
|
8 | fn print_count(matches: Matches, opts: Options) {
| ------- move occurs because `matches` has type `Matches`, which does not implement the `Copy` trait
9 | match opts.max {
10 | Some(n) if matches.count() > n => print!("{}{}", n, opts.separator),
| ------- value moved here...
News & Blog Posts
2019-07-02
~33 min read
github.com
...These fragment specifiers define what Rust syntax will be matched and bound to each metavariable. For example, the `item` fragment specifier matches an [item][], `block` matches a [block expression][], `expr` matches an [expression][], and so on.
As we add new features to Rust, sometimes we change its syntax. This means...
RFC 3531
RFC
2023-11-16
~7 min read
github.com
...Two
incredibly common patterns in particular stand out:
```
match map.entry(key) => {
Entry::Vacant(entry) => { entry.insert(1); },
Entry::Occupied(entry) => { *entry.get_mut() += 1; },
}
```
```
match map.entry(key) => {
Entry::Vacant(entry) => { entry.insert(vec![val]); },
Entry::Occupied(entry) => { entry.get_mut().push(val); },
}
```
This code is noisy, and is...
RFC 921
RFC
2015-03-01
~2 min read
dev.to
...either match everything, or using combinators: ok(), unwrap_or(), and_then(), etc, etc... I prefer to match and follow strict indentation, so that it is clearer at the end what we are matching for. We use indentation to help understanding the patterns of Ok(_)/Err(_) and Some(_)/None.
Maybe it...
Rust Walkthroughs
2020-12-02
~18 min read
mcmah309.github.io
...Option<f64>) {
self.ranking_score_threshold = threshold;
}
}
impl HasTermsMatchingStrategy for KeywordSearch<'_> {
fn get_terms_matching_strategy(&self) -> &TermsMatchingStrategy {
&self.terms_matching_strategy
}
fn set_terms_matching_strategy(&mut self, strategy: TermsMatchingStrategy) {
self.terms_matching_strategy = strategy;
}
}
impl HasScoringStrategy for KeywordSearch<'_> {
fn get_scoring_strategy(&self) -> &ScoringStrategy {
&self.scoring_strategy
}
fn...
Rust Walkthroughs
2025-06-11
~17 min read
corentin-core.github.io
...let list = hlist![1i32, "hello", 3.14f64];
let (matched, leftover) = list.sculpt::<HList!(f64, i32), _>();
// matched : HList!(3.14f64, 1i32)
// leftover : HList!("hello")
The compiler walks the source HList, plucks each requested type by recursing until it finds a match, builds the matched tuple, returns what’s left.
Two failure...
Rust Walkthroughs
2026-06-24
~16 min read