www.rismosch.com
...Job) -> Result<(), BlockedOrFull> {
let head = unsafe { &mut *self.head.get() };
let mutnode = match self.jobs[*head].try_lock() {
Ok(node) => node,
Err(std::sync::TryLockError::WouldBlock) => {
return Err(BlockedOrFull { not_pushed: job })
}
Err(std::sync::TryLockError::Poisoned(e)) => throw!("mutex is poisoned: {}", e),
};
match *node {
Some(_) => Err(BlockedOrFull { not_pushed...
Rust Walkthroughs
2022-10-12
~44 min read
pker.xyz
...Vec<CString> = vec![cmd.clone()];
argv.extend(args.iter().map(|a| CString::new(a.as_str()).unwrap()));
match execvp(&cmd, &argv) {
Ok(void) => match void {},
Err(e) => panic!("execvp failed: {e}"),
}
}
}
}
The child calls traceme() then execvp. The exec
generates a SIGTRAP that stops the child, and the parent
picks...
Project/Tooling Updates
2026-02-18
~15 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
lupyuen.github.io
...Finally we match the result returned by the C function: 0 for success, non-zero for error…
// Check the result code
match res {
0 => Ok(()), // If no error, return OK
_ => Err(res) // Else return the result code as an error
}
}
“match” works like “switch...case” in C. (“_” matches anything, similar...
Miscellaneous
2021-04-21
~25 min read
doc.rust-lang.org
...We switched from if to match now that we have three cases. We need to explicitly match on a slice of request_line to pattern-match against the string literal values; match doesn’t do automatic referencing and dereferencing, like the equality method does.
The first arm is the same...
The Rust Programming Language
Book
2024-02-01
~23 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
github.com
...pub struct Foo(SomeType);
// in downstream code
let Foo(_) = foo;
```
Changing `Foo` to a normal struct can break code that matches on it -- but there
is never any real reason to match on it in that circumstance, since you cannot
extract any fields or learn anything of interest about the...
RFC 1105
RFC
2015-05-04
~24 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
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
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
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
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
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
rust-lang-nursery.github.io
...String) -> Result<Self, String> {
let level = match value.to_lowercase().as_str() {
"info" => LogLevel::Info,
"debug" => LogLevel::Debug,
"warn" => LogLevel::Warn,
"error" => LogLevel::Error,
"trace" => LogLevel::Trace,
other => return Err(format!("Unknown log level: {}", other)),
};
Ok(level)
}
}
#[allow(dead_code)]
#[derive(Debug)]
struct Config {
server_url: String,
log_level: LogLevel...
The Rust Cookbook
Book
2024-01-01
~2 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
github.com
...Except for the cases handled below, these operations produce results that exactly match IEEE 754-2008 (with roundTiesToEven [except for float-to-int casts, which round towards zero] and default exception handling without traps, without abruptUnderflow/flush-to-zero).
`%` matches the behavior of `fmod` in C (this operation is not...
RFC 3514
RFC
2023-10-14
~26 min read