ceronman.com
...This would require changing the data layout of the structs to match C. The problem with using an enum is that a match operation is required on every dereference. I believe this match should be optimized out by the compiler, but I haven’t properly checked. But even then, struct...
Observations/Thoughts
2021-07-28
~25 min read
doc.rust-lang.org
pub const fn unwrap(self) -> T
...Instead, prefer to use pattern matching and handle the None case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_or_default. In functions returning Option, you can use the ? (try) operator.
Panics
Panics if the self value equals None.
Examples
let x = Some("air");
assert_eq!(x.unwrap...
method
core
Stable since 1.0.0
Version 1.100.0-nightly
doc.rust-lang.org
pub const fn map<U, F>(self, op: F) -> Result<U, E>
...let line = "1\n2\n3\n4\n";
for num in line.lines() {
match num.parse::<i32>().map(|i| i * 2) {
Ok(n) => println!("{n}"),
Err(..) => {}
}
}
method
core
Stable since 1.0.0
Version 1.100.0-nightly
kerkour.com
...fn do_something() -> Result<(), Error> {
let user = get_user_opt().ok_or(Error::UserNotFound)?;
// do something
}
match
Then, of course, there is match:
fn do_something() -> Result<(), Error> {
let user = match get_user_opt() {
Some(user) => user,
None => return Err(Error::UserNotFound);
};
// do something
}
if let / let else
Even better...
Observations/Thoughts
2025-11-26
~6 min read
sergey-melnychuk.github.io
...process socket events
for event in &events {
match event.token() {
Token(0) => {
loop {
match listener.accept() {
Ok((socket, _)) => {
// accept connection, create Handler
},
Err(_) => break
}
}
},
token if event.readiness().is_readable() => {
debug!("token {} readable", token.0);
if let Some(handler) = handlers.remove(&token) {
event_tx.send(handler).unwrap();
}
},
token if event...
News & Blog Posts
2020-05-05
~4 min read
docs.rs
...When searching for more than one byte, positions are considered a match if the byte at that position matches any of the bytes. The memmem sub-module provides forward and reverse substring search routines. In all such cases, routines operate on &[u8] without regard to encoding. This is exactly what...
Crate
v2.8.3
2026-07-08
crates.io
...pub enum DbDriver { Postgresql, Mysql, } impl std::str::FromStr for DbDriver { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.trim().to_lowercase().as_ref() { "postgres" => Ok(DbDriver::Postgresql), "mysql" => Ok(DbDriver::Mysql), _ => Err(format!("Unknown DB driver: {s}")) } } } #[derive(Envconfig)] pub struct DbConfig { // ... #[envconfig...
Crate
v0.11.1
2025-12-10
crates.io
...pub enum DbDriver { Postgresql, Mysql, } impl std::str::FromStr for DbDriver { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.trim().to_lowercase().as_ref() { "postgres" => Ok(DbDriver::Postgresql), "mysql" => Ok(DbDriver::Mysql), _ => Err(format!("Unknown DB driver: {s}")) } } } #[derive(Envconfig)] pub struct DbConfig { // ... #[envconfig...
Crate
v0.11.1
2025-12-10
system76.com
...System76 offers health benefits, paid vacation, matching 401k, sabbatical, and an awesome dog-friendly work environment where smart people are free to create.
We are committed to providing equal employment opportunities to all employees and applicants, regardless of race, color, creed, religion, sex, gender identity/expression, age, national origin, disabilities...
Rust Jobs
2019-01-08
~1 min read
docs.rs
...16) -> Result<Self, Self::Error> { match n { 0 => Ok(Foo::Bar), 100 => Ok(Foo::Baz), 200 => Ok(Foo::Quix), _ => Err(n), } } } fn main() { let bar = Foo::try_from(0); let baz = Foo::try_from(100); let quix = Foo::try_from(200); let bad = Foo::try_from(300); assert_eq!(bar...
Crate
v1.0.0
2020-03-30
doc.rust-lang.org
pub fn duration(&self) -> Duration
...Examples
use std::thread::sleep;
use std::time::{Duration, SystemTime};
let sys_time = SystemTime::now();
sleep(Duration::from_secs(1));
let new_sys_time = SystemTime::now();
match sys_time.duration_since(new_sys_time) {
Ok(_) => {}
Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
}
method
std
Stable since 1.8.0
Version 1.100.0-nightly
rustc-dev-guide.rust-lang.org
...Examples of such structures include but are not limited to
• Parenthesis
• Removed without replacement, the tree structure makes order explicit
• for loops
• Converted to match + loop + match
• Universal impl Trait
• Converted to generic arguments (but with some flags, to know that the user didn't write them)
• Existential impl Trait...
Guide to Rustc Development
Book
2024-01-01
~2 min read
trieve.ai
...Our algorithm prioritizes prefix matches and factors in the frequency of each candidate word within the dataset.
fn is_best_correction(word: &str, correction: &str) -> bool {
// Length-based filter
let len_diff = (word.len() as i32 - correction.len() as i32).abs();
if len_diff > 2 {
return false;
}
// Prefix matching (adjust...
Observations/Thoughts
2024-09-11
~6 min read
kerkour.com
...Vec<String>, output_dir: &str) -> Result<(), anyhow::Error> {
let mut html = templates::HEADER.to_owned();
let body = files
.into_iter()
.map(|file| {
let file = file.trim_start_matches(output_dir);
let title = file.trim_start_matches("/").trim_end_matches(".html");
format!(r#"<a href="{}">{}</a>"#, file, title)
})
.collect::<Vec<String...
Rust Walkthroughs
2021-09-29
~3 min read
doc.rust-lang.org
pub fn remove<Q>(&mut self, value: &Q) -> bool
...The value may be any borrowed form of the set's element type, but the ordering on the borrowed form must match the ordering on the element type.
Examples
use std::collections::BTreeSet;
let mut set = BTreeSet::new();
set.insert(2);
assert_eq!(set.remove(&2), true);
assert_eq!(set...
method
alloc
Stable since 1.0.0
Version 1.100.0-nightly
doc.rust-lang.org
pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
...The key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove_entry(&1), Some((1...
method
std
Stable since 1.27.0
Version 1.100.0-nightly
docs.rs
...syn::DeriveInput) -> syn::Result<TokenStream> { let attrs = Attrs::parse_attrs("from", &input)?; match (attrs.forward.is_some(), !attrs.custom.is_empty()) { (true, true) => Err(syn::Error::new_spanned( input, "`forward` and `on` arguments are mutually exclusive", )), (false, false) => Err(syn::Error::new_spanned( input, "either `forward` or `on` argument is...
Crate
v0.5.1
2026-07-22
adventures.michaelfbryan.com
...Value) -> Result<bool, Self::Error> {
match other {
Value::Bool(b) => Ok(b),
_ => Err(Error::BadVariableType),
}
}
}
impl TryFrom<Value> for i32 {
type Error = Error;
fn try_from(other: Value) -> Result<i32, Self::Error> {
match other {
Value::Integer(i) => Ok(i),
_ => Err(Error::BadVariableType),
}
}
}
impl TryFrom<Value> for f64 {
type Error = Error...
News & Blog Posts
2019-12-17
~37 min read
cantrip.org
...On earlier versions of the Rust compiler, I had to use an iterator pipeline, using .scan(), match, .filter(), and .collect(), at twice the line count, to get tolerable performance. Now the loop is faster. A match would work here, but the code would be longer. Rust could have just one...
News & Blog Posts
2016-02-01
~13 min read