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
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
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
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
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
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
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
maniagnosis.crsr.net
...So I broke down and created some macros: #[macro_export]macro_rules! unpack { ($e:expr,$m:expr) => ( match $e { Ok(v) => v, Err(e) => panic!(format!("{}: {}", $m, e.to_string())), })}#[macro_export]macro_rules! expect { ($e:expr,$m:expr) => ( match $e { Some(e) => e, None => panic!($m), })}#[macro_export]macro...
From the Blogosphere
2015-07-27
~11 min read
deepfence.io
...It usually relies on the haystack finding approach but also regular expression matching approaches. Matching happens on different parts of the HTTP message, it can be headers, port, or even HTML body. Needless to say that such operations are CPU intensive. Here is a rule example:alert http $HOME_NET...
Project/Tooling Updates
2022-07-27
~16 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
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
rsdlt.github.io
...another sequence of units based on of the dictionary.Make the Key and the Message have the same size (number of units or characters).Encode / Decode by matching each unit (or character) in the message and the key in the Vigenére table.For example:Dictionary: ABCDVigenére Matrix:ABCDBCDACDABDABCKey: DCABADMessage: BADCADEncode...
Rust Walkthroughs
2022-09-28
~18 min read
www.sheshbabu.com
...Self::Message) -> ShouldRender {
match message {
+ Msg::GetProducts => {
+ self.state.get_products_loaded = false;
+ let handler =
+ self.link
+ .callback(move |response: api::FetchResponse<Vec<Product>>| {
+ let (_, Json(data)) = response.into_parts();
+ match data {
+ Ok(products) => Msg::GetProductsSuccess(products),
+ Err(err) => Msg::GetProductsError(err),
+ }
+ });
+ self.task = Some(api::get_products(handler));
+ true...
Learn More Rust
2020-08-11
~29 min read
cryptographycaffe.sandboxaq.com
...Specifically, the properties we aim to prove ensure that the configuration defined by a Sandwich user matches what Sandwich actually sets when interacting with the cryptographic library.In this initial effort, we focused on the OpenSSL 3 version of Sandwich and defined the following security properties.Safe TLS Protocol VersionsPolicy...
Miscellaneous
2025-04-02
~9 min read
salvo.rs
...i64, } #[handler] async fn me(depot: &mut Depot, res: &mut Response) { match depot.jwt_auth_state() { JwtAuthState::Authorized => { let data = depot.jwt_auth_data::<Claims>().unwrap(); res.render(Json(&data.claims)); } JwtAuthState::Unauthorized => res.render(StatusError::unauthorized()), JwtAuthState::Forbidden => res.render(StatusError::forbidden()), } } #[tokio::main] async fn main() { let auth...
Crate
v1.2.1
2026-11-17
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
www.greyblake.com
...Vehicle) -> VehicleRecord {
let Vehicle { id , vehicle_type } = vehicle;
let (kind, fuel, max_speed_kph) = match vehicle_type {
VehicleType::Car { fuel, max_speed_kph } => {
(
"Car".to_owned(),
Some(fuel_to_str(fuel).to_owned()),
max_speed_kph.map(|speed| speed.try_into().unwrap() )
)
}
Bicycle => {
(
"Bicycle".to_owned(),
None,
None,
)
}
};
let id...
Rust Walkthroughs
2022-11-02
~7 min read