Expert knowledge for Rust systems programming covering ownership, borrowing, type safety, error handling, async patterns, performance optimization, and the 2024 edition improvements for building safe, concurrent, and high-performance applications
Expert guidance for Rust systems programming. Rust shifts runtime worries (memory safety, data races) to compile-time, enabling safe, concurrent, and high-performance code.
.clone() everywhere&str over String, &[T] over Vec<T> for function argumentsResult or Option, use ? operator for clean propagation<T: Trait> for speed, only when binary size matters&dyn Trait// Heap allocation or recursive types
let data = Box::new(value);
// Shared ownership (single-threaded)
let shared = Rc::new(value);
// Shared ownership (multi-threaded)
let shared = Arc::new(value);
// Interior mutability (mutate behind immutable reference)
let cell = RefCell::new(value);
let mut borrowed = cell.borrow_mut();
// Avoid primitive obsession
struct UserId(u32);
struct OrderId(u32);
fn get_user(id: UserId) { /* can't pass OrderId by mistake */ }
// Library: custom error types with thiserror
#[derive(thiserror::Error, Debug)]
enum MyError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Invalid input: {0}")]
Invalid(String),
}
// Application: anyhow for unified error handling
use anyhow::Result;
fn process() -> Result<()> {
let data = read_file()?;
let parsed = parse_data(data)?;
Ok(())
}
struct Locked;
struct Unlocked;
struct Door<State> {
_state: PhantomData<State>,
}
impl Door<Locked> {
fn unlock(self) -> Door<Unlocked> {
Door { _state: PhantomData }
}
}
impl Door<Unlocked> {
fn lock(self) -> Door<Locked> {
Door { _state: PhantomData }
}
}
// Native async closure syntax
let async_op = async || {
fetch_data().await
};
// Future and IntoFuture are now in prelude (no manual import needed)
| Tool | Purpose | Command |
|---|---|---|
| Cargo | Build system and package manager | cargo build |
| Clippy | Linter (700+ checks) | cargo clippy |
| Rustfmt | Code formatter | cargo fmt |
| Cargo Audit | Security vulnerability scanner | cargo audit |
| Flamegraph | Performance profiling | cargo flamegraph |