rust
12 lines · 1 tab
Marcus Chen
Jan 2026
1 tab
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let fast = sleep(Duration::from_millis(50));
let slow = sleep(Duration::from_millis(200));
tokio::select! {
_ = fast => println!("Fast completed first"),
_ = slow => println!("Slow completed first"),
}
}
1 file · rust
Explain with highlit
Tokio's select! macro lets you wait on multiple futures simultaneously, proceeding with the first one that completes. I use it for timeouts, graceful shutdown, and racing I/O operations. Each branch is a pattern match on the future's output. If multiple futures are ready, one is chosen randomly to avoid starvation. The key is that select! cancels the other branches when one completes (by dropping them). For shutdown, I race the main logic against a signal future. For caching, I race a fast cache lookup against a slow database fetch. The macro is powerful but has subtleties (like biased for priority). It's essential for writing responsive async services.
Related snips
typescript
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
typescript
reliability
retry
by codesnips
2 tabs
rust
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
rust
lifetimes
borrowing
by Marcus Chen
1 tab
rust
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
rust
concurrency
lock-free
by Marcus Chen
1 tab
javascript
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
javascript
promises
async-await
by Alex Chang
1 tab
rust
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
rust
observability
tracing
by Marcus Chen
1 tab
rust
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
rust
concurrency
channels
by Marcus Chen
1 tab
Share this code
Here's the card — post it anywhere.