crates.io
...Pin<&mut Self>) { match self.project() { EnumProj::Pinned(x) => { let _: Pin<&mut T> = x; } EnumProj::Unpinned(y) => { let _: &mut U = y; } } } } code like this will be generated See #[pin_project] attribute for more details, and see examples directory for more examples and generated code. Related Projects pin-project-lite : A...
Crate
v1.1.13
2026-05-13
crates.io
...for n in 0..100 { match circuit_breaker.call(|| dangerous_call()) { Err(Error::Inner(_)) => { eprintln!("{}: fail", n); }, Err(Error::Rejected) => { eprintln!("{}: rejected", n); break; }, _ => {} } } Or configure custom backoff and policy: use std::time::Duration; use failsafe::{backoff, failure_policy, CircuitBreaker}; // Create an exponential growth backoff which starts from 10s and...
Crate
v1.3.0
2024-07-05
mender.io
...Through utilizing the pattern matching capabilities of Rust, the initial state-machine skeleton looks like:
loop {
let (state, action) = match (cur_state, cur_action) {
(ExternalState::Init, Event::Uninitialized) => {
match InitState::is_committed() {
true => (ExternalState::Idle, Event::None),
false => (ExternalState::Idle, Event::None),
}
}
(ExternalState::Idle, _) if !client.is_authorized => {
debug!("Client...
Learn More Rust
2020-08-18
~11 min read
docs.rs
...SocketAddr = (ip, port).into(); let (name, service) = match getnameinfo(&socket, 0) { Ok((n, s)) => (n, s), Err(e) => panic!("Failed to lookup socket {:?}", e), }; println!("{:?} {:?}", name, service); let _ = (name, service); } { use dns_lookup::gethostname; let hostname = gethostname().unwrap(); }
Crate
v3.0.1
2025-10-20
doc.rust-lang.org
pub const fn cold_path()
...i32) -> i32 {
match x {
1 => 10,
2 => 100,
3 => { cold_path(); 1000 }, // this branch is unlikely
_ => { cold_path(); 10000 }, // this is also unlikely
}
}
This can also be used to implement likely and unlikely helpers to hint the condition rather than the branch:
use core::hint::cold_path;
#[inline(always)]
pub...
function
core
Stable since 1.95.0
Version 1.100.0-nightly
kmcallister.github.io
...main() {
::std::io::stdio::println_args(
::std::fmt::Arguments::new({
#[inline]
#[allow(dead_code)]
static __STATIC_FMTSTR: &'static [&'static str]
= &["Hello, world!"];
__STATIC_FMTSTR
}, &match () { () => [], }));
}
Freeze the shape of the tree
Assign each node a unique NodeId
Build an index by NodeId of AST nodes and their parents
See libsyntax...
Blog Posts
2015-01-19
~6 min read
blog.digital-horror.com
...Think of this as a simple client-server connection.loop {
match socket.read(&mut buf).await {
Ok(0) => returing,
Ok(n) => {
println!(
"received {} bytes, msg: {}",
n,
String::from_utf8_lossy(buf.clone()[..n].to_vec().as_slice())
);
socket
.write_all(&buf[..n])
.await
.expect("failed to write data to socket...
Observations/Thoughts
2024-05-29
~6 min read
docs.rs
...use tree_sitter_highlight::HighlightEvent; let highlights = highlighter.highlight( &javascript_config, b"const x = new Y();", None, |_| None ).unwrap(); for event in highlights { match event.unwrap() { HighlightEvent::Source {start, end} => { eprintln!("source: {start}-{end}"); }, HighlightEvent::HighlightStart(s) => { eprintln!("highlight style started: {s:?}"); }, HighlightEvent::HighlightEnd => { eprintln!("highlight style ended"); }, } } The last...
Crate
v0.26.11
2026-07-12
gill.net.in
...u16,
) -> Option<(Device<T>, DeviceHandle<T>)> {
let devices = match context.devices() {
Ok(d) => d,
Err(_) => return None,
};
for device in devices.iter() {
let device_desc = match device.device_descriptor() {
Ok(d) => d,
Err(_) => continue,
};
if device_desc.vendor_id() == vid && device_desc.product_id() == pid {
match device.open() {
Ok(handle...
Learn More Rust
2020-08-04
~14 min read
rust-lang-nursery.github.io
...of an array in parallel | [![rayon-badge]][rayon] | [![cat-concurrency-badge]][cat-concurrency] | | Test in parallel if any or all elements of a collection match a given predicate | [![rayon-badge]][rayon] | [![cat-concurrency-badge]][cat-concurrency] | | Search items using given predicate in parallel | [![rayon-badge]][rayon] | [![cat-concurrency-badge]][cat...
The Rust Cookbook
Book
2024-01-01
~1 min read
doc.rust-lang.org
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
...The supplied 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;
use std::hash::{Hash, Hasher};
#[derive(Clone, Copy, Debug)]
struct S {
id: u32,
name: &'static str...
method
std
Stable since 1.40.0
Version 1.100.0-nightly
doc.rust-lang.org
...is a slice to the original string, hence no new
// allocation is performed
let chars_to_trim: &[char] = &[' ', ','];
let trimmed_str: &str = string.trim_matches(chars_to_trim);
println!("Used characters: {}", trimmed_str);
// Heap allocate a string
let alice = String::from("I like dogs");
// Allocate new memory and store the...
Rust by Example
Book
2024-01-01
~4 min read
rustc-dev-guide.rust-lang.org
...Destruction scopes are also made explicit.
•
Statements, expressions, match arms, blocks, and parameters are stored separately. For example, statements in the stmts array reference expressions by their index (represented as a ExprId) in the exprs array.
The THIR lives in rustc_mir_build::thir. To construct a thir::Expr, you...
Guide to Rustc Development
Book
2024-01-01
~4 min read
whileydave.com
...usize = __nondet();
// Apply Constraints
__VERIFIER_assume(len <= LIMIT);
__VERIFIER_assume(i < len);
__VERIFIER_assume(xs[i] == x);
// Compute result
let result = index_of(&xs[..len],x);
// Check it matches
assert!(xs[result] == x);
}
This is roughly similar to before, except we now require some i
where xs[i] == x. Also...
Observations/Thoughts
2021-10-27
~6 min read
docs.rs
...let recording_rules = client.rules().kind(RuleKind::Recording).get().await; assert!(recording_rules.is_ok()); // Retrieve a list of time series that match certain labels sets ("series selectors"). let select1 = Selector::new() .eq("handler", "/api/v1/query"); let select2 = Selector::new() .eq("job", "node") .regex_eq("mode", ".+"); let time_series...
Crate
v0.9.0
2026-05-09
doc.rust-lang.org
...Code that looked like this:
// Rust 2015
extern crate futures;
use futures::Future;
mod foo {
pub struct Bar;
}
use foo::Bar;
fn my_poll() -> futures::Poll { ... }
enum SomeEnum {
V1(usize),
V2(String),
}
fn func() {
let five = std::sync::Arc::new(5);
use SomeEnum::*;
match ... {
V1(i) => { ... }
V2(s) => { ... }
}
}
will look...
The Rust Edition Guide
Book
2024-01-01
~7 min read
gekkio.fi
...let op = read_op();
match op {
// ...
0xC1 => { // POP BC
cpu.bc = mem_read_u16(cpu.sp);
cpu.sp += 2;
cpu.cycles += 3;
},
0xC5 => { // PUSH BC
cpu.sp -= 2;
mem_write_u16(cpu.sp, cpu.bc);
cpu.cycles += 4;
}
// ...
}
This might seem perfectly fine, but is actually inaccurate if we look...
Blog Posts
2015-01-19
~4 min read
www.shuttle.rs
...We want to check the row with that username has a password that matches. If the credentials match then we create a new session:
Then we refer back to the signup section and replicate the same HTML form and handler that renders the Tera template as seen before but for...
Observations/Thoughts
2022-08-31
~12 min read
app.codecrafters.io
...for stream in listener.incoming() {
match stream {
Ok(stream) => {
// handle the connection
}
Err(e) => {
eprintln!("Failed: {}", e);
}
}
}
The TcpStream struct
The iterator returned from TcpListener::incoming yields instances of TcpStream.
Some important methods associated with the TcpStream struct are:
impl TcpStream {
// read reads bytes from the stream
pub fn read...
Miscellaneous
2024-04-24
~3 min read
github.com
...u64 = match r.payload { j::ResponsePayload::Success(val) => serde_json::from_str(val.get()).unwrap(), j::ResponsePayload::Failure(err) => panic!("unexpected error: {err}"), }; assert_eq!(n, 12345); } Low-level Ethereum JSON-RPC transport abstraction. This crate handles RPC connection and request management. It builds an RpcClient on top of the...
Crate
v2.4.1
2026-08-13