doc.rust-lang.org
...match self.0.front_mut().and_then(Iterator::next) {
Some(State::Elem(elem)) => return Some(elem),
Some(State::Node(node)) => self.0.push_front(node.iter_mut()),
None => {
self.0.pop_front()?;
}
}
}
}
}
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
fn next_back(&mut self) -> Option<Self::Item> {
loop {
match...
The Rustonomicon
Book
2024-01-01
~5 min read
fasterthanli.me
...Args = argh::from_env();
let mut file = File::open(&args.file)?;
let mut hasher = sha3::Sha3_256::new();
let mut buf = vec![0u8; 256 * 1024];
loop {
let n = file.read(&mut buf[..])?;
match n {
0 => break,
n => hasher.update(&buf[..n]),
}
}
let hash = hasher.finalize();
print!("{} ", args.file.display());
for...
Learn Standard Rust
2020-08-11
~42 min read
fasterthanli.me
...usize = 5;
loop {
let res = self
.inner
.execute(req.try_clone().unwrap())
.await
.and_then(|r| r.error_for_status());
match res {
Err(e) if tries > 1 => {
tries -= 1;
log::error!("{}", e);
tokio::time::delay_for(Duration::from_secs(1)).await;
}
res => return res,
}
}
}
}
You’re pleased with how easy...
News & Blog Posts
2020-07-14
~21 min read
nnmm.github.io
...To make it work for types and literals, I added match arms with a tag in front to make sure we don’t accidentally match the wrong arm:
macro_rules! choose_xtal {
(ty Xtal => $a:ty, Tha => $b:ty) => {
$a
};
(literal Xtal => $a:literal, Tha => $b:literal) => {
$a
};
(Xtal => $a...
Observations/Thoughts
2023-01-18
~5 min read
michaelwoerister.github.io
...int, tail: ~LinearList },
Nil
}
fn traverse(list: &LinearList) -> Iterator<int> {
match *list {
Node { data: data, tail: ~ref tail } => {
yield return data;
// Recursively iterate
for item in traverse(tail) {
yield return item;
}
}
Nil => {
yield break;
}
}
}
With the code above every call to the outer iterator traverses every nesting level until the...
Discussion + Blog posts
2013-08-10
~5 min read
www.hoverbear.org
...let chunk = splits.next()
.and_then(|v| v.parse::<u64>().ok());
match chunk {
Some(v) => v,
None => return Err(io::Error::new(io::ErrorKind::InvalidInput, "Could not parse term.", None)),
}
};
let encoded = {
let chunk = splits.next();
match chunk {
Some(v) => v,
None => return Err(io::Error::new(io::ErrorKind::InvalidInput...
Project Updates
2015-02-23
~8 min read
ticki.github.io
...for c in stdin.events() {
let evt = c.unwrap();
match evt {
Event::Key(Key::Char('q')) => break,
Event::Mouse(me) => {
match me {
MouseEvent::Press(_, a, b) |
MouseEvent::Release(a, b) |
MouseEvent::Hold(a, b) => {
write!(stdout, "{}", cursor::Goto(a, b)).unwrap();
}
}
}
_ => {}
}
stdout.flush().unwrap();
}
}
Now, if you click around or...
Blog Posts
2016-10-11
~8 min read
rocket.rs
...Enable matching of static query components. No special-casing of any kind, preferring type-driven flows. Ad-hoc matching of specific query key/value pairs. Lenient parsing by default, allowing missing parameters. Order-independent matching of query parameters. To illustrate the new system in action, consider the following route: 1...
News & Blog Posts
2018-12-11
~12 min read
adventures.michaelfbryan.com
...how do we want to handle overflows?
let _ = self.decoder.push_data(inputs.receive());
loop {
match self.decoder.decode() {
Ok(pkt) => unimplemented!("B: What do we do now?"),
Err(DecodeError::InvalidCRC) => {
unimplemented!("C: How do we handle corrupted packets?")
},
Err(DecodeError::RequiresMoreData) => break,
}
}
}
}
This looks fairly straightforward, but it’s...
News & Blog Posts
2019-10-08
~9 min read
std.rs
...to a variable.loopLoop indefinitely.matchControl flow based on pattern matching.modOrganize code into modules.moveCapture a closure’s environment by value.mutA mutable variable, reference, or pointer.pubMake an item visible to others.refBind by reference during pattern matching.returnReturns a value from a function.selfThe receiver of a...
News & Blog Posts
2020-01-28
~12 min read
besok.github.io
...I eventually settled on this setup:zig build test # run all tests
zig build test -Dfilter="filter match function basic" # run one test
zig build test -Ddebug-query=true # all tests with debug
zig build compliance # compliance suite
zig build check # unit tests + compliance
Once you accept the terms, it...
Observations/Thoughts
2026-08-19
~12 min read
arzg.github.io
...This is easy to fix:impl Expr {
// snip
pub(crate) fn eval(&self) -> Val {
match self {
Self::Number(Number(n)) => Val::Number(*n),
Self::Operation { lhs, rhs, op } => {
let Number(lhs) = lhs;
let Number(rhs) = rhs;
let result = match op {
Op::Add => lhs + rhs,
Op::Sub => lhs - rhs,
Op::Mul...
Learn More Rust
2020-10-07
~18 min read
contextgeneric.dev
...However, Rust’s powerful enum and match features often reduce the need for the visitor pattern, especially when the concrete enum type is known. In such cases, developers can simply use match expressions to handle each variant explicitly and concisely.
Despite this, the visitor pattern remains useful in situations where...
Observations/Thoughts
2025-07-09
~38 min read
stackoverflow.blog
...Here's an example of a function to greet someone whether or not we know their name; if we had forgotten the None case in the match or tried to use name as if it was an always-present String value, the compiler would complain.fn greet_user(name: Option...
News & Blog Posts
2020-01-21
~9 min read
rust.code-maven.com
...u32 = match cookies.get("counter") {
Some(cookie) => match cookie.value().parse() {
Ok(val) => val,
Err(_) => {
eprintln!("Invalid value '{}' for the 'counter' cookie.", cookie.value());
0
},
},
None => 0,
};
let counter = counter + 1;
cookies.add(("counter", counter.to_string()));
format!("Counter: {}", counter)
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
#[cfg(test...
Miscellaneous
2024-01-10
~8 min read
blog.sheerluck.dev
...Direction) -> bool {
matches!(
(a, b),
(Direction::Up, Direction::Down)
| (Direction::Down, Direction::Up)
| (Direction::Left, Direction::Right)
| (Direction::Right, Direction::Left)
)
}
matches! is a Rust macro that checks if a value matches a pattern.
Snake Movement
This is the core logic that runs on each timer tick:
fn snake_move...
Rust Walkthroughs
2026-06-03
~18 min read
parsa.wtf
...StateStack,
) -> Termination {
match lex.peek(store) {
_ => raise_diagnostic(store, lex, emit, stack, DiagnosticKind::E079),
}
}and now the reveal:
> x -b --fn ForOrInOfStatement 1
000000000021e290 <joe::fe::parser_handlers::ForOrInOfStatement>:
21e290: ff c6 inc esi
21e292: 89 f0 mov eax,esi
21e294: 83 e0 3f and eax,0x3f
21e297: 0f b6...
Observations/Thoughts
2026-07-08
~8 min read
eno.space
...That looks suspiciously like an enum …
So let’s rewrite our program and use an enum instead of structs, using match to destructure the enum instead of dynamic dispatch.
use std::cell::Cell;
enum Sum<'a> {
Sum(Box<Sum<'a>>, Box<Sum<'a>>),
Constant(i32),
Variable(&'a Cell<i32>),
}
impl...
News & Blog Posts
2018-02-20
~12 min read
www.wilfred.me.uk
...We can use any of +-<>.,[] safely,
as long as our brackets are matched.]
actual code here!
bfc aggressively removes dead code. For example, cells in BF are
initialised to zero, so a loop at the beginning of a program is dead:
[dead]not-dead
We also know that if a...
From the Blogosphere
2015-08-31
~9 min read
www.ncameron.org
...I would very much like to see quasi-quoting and pattern matching in blessed libraries. These are important tools, the former currently provided by libsyntax. I don't see any reason these must be provided by libmacro, and since quasi-quoting produces AST, they probably can't be (since they...
News & Blog Posts
2015-11-30
~9 min read