Rust ownership, borrowing, lifetimes, error handling, async programming, concurrency patterns, and idiomatic Rust. Use when writing, reviewing, or debugging Rust code.
"In Rust, the compiler is your strictest code reviewer and your most reliable safety net."
// Transfer ownership
fn process(data: Vec<u8>) { /* owns data, dropped at end */ }
// Borrow immutably
fn analyze(data: &[u8]) -> usize { data.len() }
// Borrow mutably
fn transform(data: &mut Vec<u8>) { data.push(0); }
// Return owned data
fn create() -> Vec<u8> { vec![1, 2, 3] }
// Explicit lifetime: output borrows from input
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
// Struct holding a reference
struct Parser<'a> {
input: &'a str,
position: usize,
}
// When in doubt, make it owned
// Use String instead of &str in structs unless you have a clear lifetime story
let s: &'static str = "hello";use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Database error: {0}")]
Database(#[from] sqlx::Error),
#[error("Not found: {entity} with id {id}")]
NotFound { entity: &'static str, id: String },
#[error("Validation failed: {0}")]
Validation(String),
#[error(transparent)]
Unexpected(#[from] anyhow::Error),
}
thiserror for library error types (structured, typed errors)anyhow for application-level error handling (convenient, context-rich).context("what was being done") from anyhow? operator for propagation; avoid explicit match on every Result// Spawning concurrent tasks
let (a, b) = tokio::join!(fetch_users(), fetch_orders());
// Spawning independent tasks
let handle = tokio::spawn(async move {
process(data).await
});
let result = handle.await?;
// Select first to complete