crates.io
...mind the trailing newline! match rulelist("a = b / c\nc = *(d e)\n") { Ok(rules) => println!("{:#?}", rules), Err(error) => eprintln!("{}", error), } outputs [ Rule { name: "a", node: Alternatives( [ Rulename( "b", ), Rulename( "c", ), ], ), kind: Basic, }, Rule { name: "c", node: Repetition { repeat: Variable { min: None, max: None, }, node: Group( Concatenation( [ Rulename( "d", ), Rulename...
Crate
v0.13.0
2022-10-21
doc.rust-lang.org
pub fn var_os<K>(key: K) -> Option<crate::ffi::OsString>
...Examples
use std::env;
let key = "HOME";
match env::var_os(key) {
Some(val) => println!("{key}: {val:?}"),
None => println!("{key} is not defined in the environment.")
}
If expecting a delimited variable (such as PATH), split_paths can be used to separate items.
function
std
Stable since 1.0.0
Version 1.100.0-nightly
git-cliff.org
...See #555 for an example.
✂️ Trim Text
We changed the commit parser behavior to always trim the text (commit message, body, etc.) before matching it with a regex.
This means that you will be able to use $ in the regex for matching until the end.
For example:
[git]commit_parsers...
Project/Tooling Updates
2024-04-03
~2 min read
dev.to
...impl AgentError {
pub fn is_retryable(&self) -> bool {
matches!(
self,
Self::Network(_) | Self::Provider { status: Some(500..=599), .. }
)
}
pub fn is_client_error(&self) -> bool {
matches!(self, Self::Provider { status: Some(s), .. } if *s >= 400 && *s < 500)
}
}
Enter fullscreen mode
Exit fullscreen mode
This was one of the things Rust...
Project/Tooling Updates
2026-03-11
~5 min read
www.coralbark.net
...The first version of my Python script just tried to match a regular expression against each line. It took over 4 minutes on my sample data, so I made a few tweaks (e.g. I noticed I was compiling the regular expression for each line). It still took over 4...
Observations/Thoughts
2020-10-21
~4 min read
arXiv
arxiv.org
...These guarantees come from a strong ownership-based type system, as well as primitive support for features like closures, pattern matching, etc., that make the code more concise and amenable to reasoning. These unique Rust features also pose a steep learning curve for programmers.
This paper presents a tool called...
Software Engineering
Pantazis Deligiannis, Akash Lal, Nikita Mehrotra et al.
2023-08-09
arXiv:2308.05177
xd009642.github.io
...Error,
{
let mut start = None;
while let Some(Ok(msg)) = receiver.next().await {
if let Ok(text) = msg.into_text() {
match serde_json::from_str::<RequestMessage>(&text) {
Ok(RequestMessage::Start(start_msg)) => {
info!(start=?start, "Initialising streamer");
start = Some(start_msg);
break;
}
Ok(RequestMessage::Stop(_)) => {
warn!("Unexpected stop received as...
Rust Walkthroughs
2025-01-22
~11 min read
docs.rs
...Visitor>(&self, visitor: &mut V) -> ControlFlow<V::Break> { match self { Self::A() => {} Self::B(_1, _2) => { _1.visit(visitor)?; _2.visit(visitor)?; } Self::C { named } => { named.visit(visitor)?; } } ControlFlow::Continue(()) } } Some types may wish to call a corresponding method on the visitor: #[derive(Visit, VisitMut)] #[visit(with = "visit_expr")] enum...
Crate
v0.5.0
2026-02-10
docs.rs
...The "Type", "Subtype" and "BaseFont" tags // are straight out of the PDF spec. // // The dictionary macro is a helper that allows complex // key-value relationships to be represented in a simpler // visual manner, similar to a match statement. // A dictionary is implemented as an IndexMap of Vec<u8>, and Object...
Crate
v0.44.0
2026-07-10
crates.io
...impl MyBehavior for MyBehaviorEnum { fn my_trait_method(&self) { match self { MyImplementorA(inner) => inner.my_trait_method(), MyImplementorB(inner) => inner.my_trait_method(), } } } Additional trait methods would be expanded accordingly, and additional enum variants would correspond to additional match arms in each method definition. It's easy to see how...
Crate
v0.3.13
2024-03-28
durka.github.io
...fn main() {
let dir = PathBuf::from(env::args().skip(1).next().unwrap());
match local_du(&dir) {
Ok(bytes) => println!("{} {}", bytes, dir.display()),
Err(error) => println!("ERROR: {:?}", error),
}
}
v1: quick and dirty
Here is the first version of my local_du function. You’ll notice that I like chaining iterators. The...
News & Blog Posts
2017-08-15
~7 min read
recursion.wtf
...let result = recursive_tree.collapse_layers(|expr| {
use ExprLayer::*;
match expr {
Add { a, b } => a + b,
Sub { a, b } => a - b,
Mul { a, b } => a * b,
LiteralInt { literal } => literal,
}
})
Expand and Collapse in a Single Pass
As a reminder, the RecursiveTree representing (5 - 3) * (3 + 12) looks like this:
Here...
Observations/Thoughts
2022-10-12
~7 min read
doc.rust-lang.org
pub struct Utf8Error
...FnMut(&str) {
loop {
match std::str::from_utf8(input) {
Ok(valid) => {
push(valid);
break
}
Err(error) => {
let (valid, after_valid) = input.split_at(error.valid_up_to());
unsafe {
push(std::str::from_utf8_unchecked(valid))
}
push("\u{FFFD}");
if let Some(invalid_sequence_length) = error.error_len() {
input = &after_valid...
struct
core
Stable since 1.0.0
Version 1.100.0-nightly
doc.rust-lang.org
pub fn code(&self) -> Option<i32>
...Examples
use std::process::Command;
let status = Command::new("mkdir")
.arg("projects")
.status()
.expect("mkdir command should execute successfully");
match status.code() {
Some(code) => println!("Exited with status code: {code}"),
None => println!("Process terminated by signal")
}
method
std
Stable since 1.0.0
Version 1.100.0-nightly
postacnormalna.pl
...Dlatego zaczynamy od match. Zwróćmy uwagę na słowo kluczowe ref w ramieniu Some(ref base_obj). Dzięki temu Rust nie krzyczy. Jeśli je pominiemy, wypluje taki błąd:
match self.base_template {
| ^^^^^^^^^^^^^^^^^^ help: consider borrowing here: `&self.base_template`
49 | Some(base_obj) => {
| --------
| |
| data moved here
| move occurs because `base_obj...
Rust Walkthroughs
2020-11-18
~11 min read
tweedegolf.nl
...So there are a lot of code patterns that get optimized for us.For example:pub fn process_command() {
match get_command() {
CommandId::A => send_response(123),
CommandId::B => send_response(456),
}
}
Once compiled with optimizations turned on, the compiler generates the following assembly:; x86-64
process_command:
push rax...
Rust Walkthroughs
2026-04-15
~11 min read
ianjk.com
...If it succeeds we insert the component with component_vec[entity] = Some(component); and return;
What if a component_vec doesn't exist in the World yet? Let's handle that case by creating a new component_vec if there isn't a matching one:
/* continued from above */
// No matching...
Rust Walkthroughs
2021-03-24
~12 min read
rust-analyzer.github.io
#8156 correctly lower `TraitRef`s with default params.
#8144 (first contribution) fix crash when trying to display closure types.
#8142 hide incorrect ref match completions for struct fields/methods.
#8138 set up a search scope when searching for MBE macro references.
#8159 try to ignore proc-macro stdout to prevent...
Project/Tooling Updates
2021-03-31
~1 min read
fredrik.anderzon.se
...if let Ok(num) = _req.param("id").unwrap().parse::<i16>() {
match _req.param("action").unwrap() {
"toggle" => {
store.dispatch( Todos( Toggle(num) ) )
},
"remove" => store.dispatch( Todos( Remove(num) ) ),
_ => (),
}
} else {
// Otherwise look for a show action
match _req.param("action").unwrap() {
"show" => {
match _req.param("id").unwrap() {
"all" => store.dispatch( Visibility( ShowAll...
News & Blog Posts
2016-07-19
~33 min read
crates.io
...proc_macro::TokenStream, ) -> proc_macro::TokenStream { let config = match from_tokenstream::<Config>(&TokenStream::from(attr)) { Ok(c) => c, Err(err) => return err.to_compile_error().into(), }; ... } See the serde documentation for the full range of controls that can be applied to types and their members. Error Handling Errors indicate the...
Crate
v0.3.0
2026-07-20