use tokio::time::{sleep, Duration};
async fn fetch_data() -> String {
sleep(Duration::from_millis(100)).await;
"data".to_string()
}
#[tokio::main]
async fn main() {
let result = fetch_data().await;
println!("Fetched: {}", result);
}
Rust's async/await syntax lets you write asynchronous code that looks synchronous. An async fn returns a Future, which is a lazy computation. Calling .await yields control until the future is ready, allowing other tasks to run. Tokio is the most popular async runtime; it provides a scheduler, timers, and async I/O primitives. The key is that async is zero-cost: futures compile to state machines, and there's no heap allocation per task. I use async for network servers, database clients, and any I/O-heavy workload. The ergonomics are similar to Go or Node.js, but with Rust's safety guarantees. The catch is that async Rust has a steeper learning curve (lifetimes in futures, Send bounds), but it's worth it for high-performance services.
Related snips
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
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
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
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
Share this code
Here's the card — post it anywhere.