andidog.de
...Here’s how I could match
State::Failed(String):
$enum_name::$enum_variant(..) => $int_value
Note that this is not a solution because now it won’t match State::Succeeded and State::Timeout anymore (maybe it
used to work earlier), but this article is more about getting to
understand the...
Blog Posts
2016-11-01
~4 min read
academy.fpblock.com
...an uninhabited type (Infallible or a custom enum Never {}), and
an exhaustive match over that type.
We'll implement this using a macro:
macro_rules! absurd {
($x:expr) => {
match $x {}
};
}
This matches the meaning from Haskell: given a value of an uninhabited type, we can produce any type we want...
Miscellaneous
2025-11-19
~21 min read
blog.davimiku.com
...match guardsThe if keyword after the match variable is a match guard. This arm of the match expression is only matched if the match guard is true.
We've introduced a new function, tokenize_float. Time to implement this:
fn tokenize_float(chars: &Vec<char>, curr_idx: &mut usize) -> Result...
Rust Walkthroughs
2024-11-13
~43 min read
fasterthanli.me
...Sure! But you can match the “scrutinee” (x in match x { ... }) with various
patterns, in various “arms” (true => {}, false => {} in the example above).
use rand::Rng;
fn main() {
let msg = match rand::thread_rng().gen_range(0..=10) {
// match only 10
10 => "Overwhelming victory",
// match anything 5 or above
5...
Observations/Thoughts
2022-02-16
~42 min read
rust-lang.github.io
...Rust already allows similar syntax for destructuring in pattern matches: a pattern match can use SomeStruct { field1, field2 } => ... to match field1 and field2 into values with the same names. This RFC introduces symmetrical syntax for initializers.
A family of related structures will often use the same field name for a...
RFC 1682
RFC
2016-07-18
~6 min read
dystroy.org
...while !(maze.is_won() || maze.is_lost()) {
renderer.write(w, &maze)?;
w.flush()?;
let e = event::read();
match e {
Ok(Event::Key(key_event)) => match key_event.into() {
key!(q) | key!(ctrl-c) | key!(ctrl-q) => {
return Ok(());
}
key!(up) => maze.try_move_up(),
key!(right) => maze.try_move_right...
Observations/Thoughts
2022-08-03
~3 min read
www.joshmcguigan.com
...In a larger program this type of match pattern would get repeated many times, and this is exactly why the ? operator was introduced.
use std::fs::File;
fn main() {
let file : File = match File::open("filename") {
Ok(file) => file,
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(9);
}
};
// do something...
News & Blog Posts
2019-02-12
~5 min read
rust-analyzer.github.io
#15118 (first contribution) follow raw pointers in autoderef chain when resolving methods with custom receiver.
#15235 (first contribution) don’t insert semicolon when extracting match arm.
#15226 make Expand glob import work on enum imports.
#15211 support GATs in bounds for associated types.
#15223 don’t show unresolved-field diagnostic...
Project/Tooling Updates
2023-07-12
~1 min read
danielkeep.github.io
...You can only match against literals and grammar constructs which can be captured by macro_rules!.
You cannot match unbalanced groups.
It is important, however, to keep the macro recursion limit in mind. macro_rules! does not have any form of tail recursion elimination or optimisation. It is recommended that...
Rust Compiler Performance Triage
2022-04-06
~1 min read
dev.to
...Vec<&str> = tokens[0].splitn(3, "").collect();
let choice = bookmark_tokens[2].to_string().parse::<usize>();
match choice {
Ok(choice) => {
let bookmark_pos = choice - 1;
if bookmark_pos < locations.len() {
let listing = locations[bookmark_pos].clone();
let data = visit(&listing.domain, &listing.port, &listing.file_path);
match data {
Ok(data...
Rust Walkthroughs
2020-11-04
~11 min read
zed.dev
...let mut matching_paths = matching_paths_rx
.take(MAX_SEARCH_RESULT_FILES + 1)
.collect::<Vec<_>>()
.await;
// ... then loops over the filepaths in chunks of 64...
for matching_paths_chunk in matching_paths.chunks(64) {
let mut chunk_results = Vec::new();
for matching_path in matching_paths_chunk {
// .... opens each file...
Rust Walkthroughs
2024-04-10
~12 min read
blog.jeffsmits.net
...Within a pattern match a variable may occur multiple times, and can be bound by one of those occurrences and matched against in the other places. The bug in the original attempt at implementing pattern matching was that bindings were directly mutated during pattern matching. So the pattern matching code...
News & Blog Posts
2017-08-08
~23 min read
doc.rust-lang.org
...i32) -> i32 {
match self {
Self::Add => x + y,
Self::Subtract => x - y,
}
}
}
To learn more about enums and type aliases, you can read the stabilization report from when this feature was stabilized into Rust.
See also:
match, fn, and String, "Type alias enum variants" RFC
Rust by Example
Book
2024-01-01
~1 min read
doc.rust-lang.org
...Parse(ParseIntError),
}
impl fmt::Display for DoubleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
DoubleError::EmptyVec =>
write!(f, "please use a vector with at least one element"),
// The wrapped error contains additional information and is available
// via the source() method.
DoubleError::Parse(..) =>
write!(f, "the provided...
Rust by Example
Book
2024-01-01
~1 min read
rust-analyzer.github.io
...members".
#9700 remove the legacy macro scoping hack.
#9722 refine the targets of the "Extract function" assist.
#9728 attach comma token to MATCH_ARM instead of MATCH_ARM_LIST.
#9742 fix hover range for derive inputs.
#9739 favor dereffed types in "Generate function" assist.
#9747 wrap inner tail expressions in...
Project/Tooling Updates
2021-08-04
~1 min read
doc.rust-lang.org
...Send>) | | &Type&mut Type | reference types | | *mut Type*const Type | raw pointer types | | fn(…) -> Type | function pointer types | | _ | inferred type, inferred const | | '_ | placeholder lifetime | | ! | never type |
Patterns
[Patterns] are used to match values.
| Pattern | Use | |-----------------------------------|-----| | "foo", 'a', 123, 2.4, … | literal patterns | | ident | identifier patterns | | _ | wildcard pattern | | .. | rest pattern | | a...
The Rust Reference
Book
2024-01-01
~9 min read
blog.scottlogic.com
...Rust’s pattern matching, with ranges, is an ideal tool for implementing this. Here’s an example that uses range matching to implement the jump instruction:
fn process_opcode(&mut self, opcode: u16) {
match (opcode) {
0x1000 ... 0x1FFF => self.pc = opcode & 0x0FFF,
// match other ranges to process other opcodes.
_ => ()
}
}
However, not...
News & Blog Posts
2017-12-19
~12 min read
hackeryarn.com
...A macro has to always take and produce a token tree, and that's exactly what our match arms represent. As far as macros care, all of the tree operators are interchangeable. So we could write our match arm as:
{ from $db:ident select $( $field:ident ),+ where $($test_field:ident...
Rust Walkthroughs
2025-10-08
~6 min read
bluss.github.io
...impl List {
fn walk_the_list(&mut self) {
let mut current = self;
loop {
match current.next {
None => return,
Some(ref mut inner) => current = inner,
}
}
}
}
Looks good? Rustc disagrees! (compile in the playground)
error: cannot borrow `current.next.0` as mutable more than once at a time [E0499]
Some(ref mut...
News & Blog Posts
2015-10-12
~2 min read
blog.yoshuawuyts.com
...The compiler
would be able to lower the hashmap to a fixed-sized array containing
Option<String> which uses match to access the data within 4:
pub struct HashMap {
inner: [Option<String>; 4],
}
impl HashMap {
pub fn insert(&mut self, key: KeyName, value: String) -> Option<String> {
match key {
KeyName::ContentType...
Rust Walkthroughs
2021-05-19
~11 min read