Advanced Rust: Async, Unsafe, Macros and Performance
Advanced Rust for senior developers: async and futures, unsafe code and FFI, advanced traits, declarative and procedural macros, memory layout, performance and atomics.
Study this lesson with its quizzes on Brainbotox →
Async Rust: futures, executors and Pin
An async fn in Rust returns a future: a state machine that does nothing until an executor polls it. The language provides the syntax; the runtime (Tokio, for example) comes from a crate.
The Future trait
trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
// Poll::Ready(value) or Poll::PendingWhen a future returns Pending, it has stored the waker from the context. When the awaited event happens, the waker tells the executor to poll again.
Using a runtime
#[tokio::main]
async fn main() {
let (a, b) = tokio::join!(load("a"), load("b")); // concurrently
let task = tokio::spawn(async move { compute().await });
let result = task.await.unwrap();
}| Tool | Behaviour |
|---|---|
.await | Suspends the current task until the future is ready |
join! | Runs futures concurrently and waits for all |
select! | Waits for the first to finish and drops the others |
spawn | Starts an independent task; needs a Send + 'static future on a multi-thread runtime |
Cancellation by drop
Dropping a future cancels it: it simply stops at its last .await point. Code must tolerate being abandoned at any await (cancellation safety).
Do not block the executor
std::thread::sleep or heavy CPU work inside an async task stalls every task on that worker thread. Use the async version (tokio::time::sleep) or spawn_blocking. Also avoid holding a std::sync::Mutex guard across an .await.Pin
The state machine generated for an async block can contain references to its own fields. Moving it in memory would invalidate them. Pin<P> guarantees that the pointed value will not move again. Types that are safe to move anyway implement Unpin. In practice you meet it as Box::pin(future) or the pin! macro.
Check yourself
- What happens when you call an async fn without awaiting it?
- What does Future::poll return?
- Where does the async runtime in Rust come from?
- Why is std::thread::sleep harmful inside an async task?
- What does Pin guarantee?
- How is a Rust future cancelled?
Unsafe Rust, raw pointers and FFI
The unsafe keyword unlocks a small set of operations the compiler cannot verify, and makes the programmer responsible for upholding memory safety there. It does not switch off the borrow checker.
The five unsafe abilities
- Dereference a raw pointer (
*const T,*mut T). - Call an unsafe function or method.
- Access or modify a mutable static variable.
- Implement an unsafe trait (such as
SendorSyncby hand). - Access the fields of a
union.
let mut x = 10;
let p = &mut x as *mut i32; // creating a raw pointer is safe
unsafe {
*p += 1; // dereferencing it is not
}Undefined behaviour
Inside unsafe you must never cause undefined behaviour (UB): dereferencing a dangling or null pointer, creating two &mut to the same data, reading uninitialised memory, a data race, or producing an invalid value such as a bool that is neither 0 nor 1. UB can break code far from the unsafe block.
Safe abstractions
unsafe small, wrap it in a safe API whose invariants make misuse impossible, and document why each block is sound with a // SAFETY: comment. Vec, Mutex and Rc are built this way.cargo miri test) to detect many kinds of undefined behaviour.FFI: calling C
#[repr(C)]
struct Point { x: f64, y: f64 }
unsafe extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
let n = unsafe { abs(-3) };
}
#[unsafe(no_mangle)]
pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b } // callable from Cextern "C"selects the C calling convention.#[repr(C)]gives a struct the C field layout. Without it, Rust may reorder fields.- Use
CStringandCStrfor C strings, which are null-terminated. - A panic must not unwind across an FFI boundary.
Check yourself
- An unsafe block disables the borrow checker.
- Which operation requires unsafe?
- What does #[repr(C)] do?
- What is the recommended way to use unsafe code?
- Which tool detects many cases of undefined behaviour in tests?
- Which of these is undefined behaviour?
Advanced Rust traits and the type system
Beyond basic traits, Rust offers associated types, const generics, blanket implementations, marker traits and trait objects with specific rules. Together they let you encode invariants in types at zero run-time cost.
Associated types versus generic parameters
trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; }
trait From<T> { fn from(value: T) -> Self; }| Associated type | Generic parameter | |
|---|---|---|
| Implementations per type | One | Many (From<u8>, From<&str>) |
| Chosen by | The implementor | The caller |
Trait objects and dyn compatibility
A trait can be used as dyn Trait only if it is dyn compatible (historically "object safe"): its methods must not be generic and must not return Self, unless they are excluded with where Self: Sized. Clone is therefore not usable as dyn Clone.
Sized and ?Sized
Generic parameters are Sized by default: their size is known at compile time. str, [T] and dyn Trait are unsized and live behind a pointer. Write T: ?Sized to accept them.
Blanket implementations and the newtype pattern
impl<T: std::fmt::Display> ToString for T { /* ... */ } // for every Display type
struct Meters(f64); // newtype: a distinct type with no run-time cost
struct Wrapper(Vec<String>); // lets you implement foreign traits on itConst generics
fn sum<const N: usize>(xs: [i32; N]) -> i32 { xs.iter().sum() }Marker traits and PhantomData
Send,Sync,Copy,Sized,Unpinhave no methods: they mark a property.PhantomData<T>is a zero-sized field that tells the compiler a type logically owns or usesT, for lifetimes, variance and the typestate pattern.
struct Connection<State> { _s: std::marker::PhantomData<State> }
struct Open; struct Closed;
impl Connection<Open> { fn send(&self) { } } // send exists only when openGeneric associated types
GATs allow an associated type to have its own generic parameters, typically a lifetime: type Item<'a> where Self: 'a;. They make lending iterators expressible.
Check yourself
- When should a trait use an associated type and not a generic parameter?
- Why can Clone not be used as dyn Clone?
- What does T: ?Sized allow?
- What is the newtype pattern?
- What is PhantomData<T>?
- What do const generics allow?
Rust macros: macro_rules and procedural macros
Macros are code that writes code at compile time. Rust has declarative macros, written with macro_rules!, and procedural macros, which are Rust functions that transform token streams.
Why macros exist
Functions take a fixed number of typed arguments. Macros can accept a variable number of arguments, new syntax, and generate items such as trait implementations. println!, vec! and #[derive(Debug)] are all macros.
Declarative macros
macro_rules! max {
($x:expr) => { $x };
($x:expr, $($rest:expr),+) => {
{ let a = $x; let b = max!($($rest),+); if a > b { a } else { b } }
};
}
let m = max!(3, 9, 4);| Fragment | Matches |
|---|---|
$x:expr | An expression |
$n:ident | An identifier |
$t:ty | A type |
$($x:expr),* | Zero or more, separated by commas |
macro_rules! macros are hygienic for local variables: a variable created inside the macro cannot clash with one of the same name at the call site.Procedural macros
| Kind | Looks like | Example |
|---|---|---|
| Derive | #[derive(Serialize)] | serde |
| Attribute | #[tokio::main] | Rewrites the item it decorates |
| Function-like | sql!(SELECT ...) | Custom syntax |
#[proc_macro_derive(Hello)]
pub fn hello_derive(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
let name = &ast.ident;
quote::quote! {
impl Hello for #name {
fn hello() { println!("Hello from {}", stringify!(#name)); }
}
}.into()
}- They live in a separate crate with
proc-macro = trueinCargo.toml. - They receive and return a
TokenStream. Thesyncrate parses it andquotegenerates code. - They run inside the compiler, so they can do anything at build time, and they increase compile times.
cargo expand to see the code a macro generates. Prefer a function or a generic when one is enough: macros are harder to read and debug.Check yourself
- When are Rust macros expanded?
- Which keyword defines a declarative macro?
- What does the fragment specifier $x:expr match?
- What do procedural macros operate on?
- Which crates are commonly used to write procedural macros?
- Why is println! a macro and not a function?
Rust memory layout and performance tuning
Rust gives precise control over where data lives and how it is laid out, and its abstractions compile away, but only optimised builds show that speed.
How common types are laid out
| Type | Size on a 64-bit machine | Contents |
|---|---|---|
&T, Box<T> | 8 bytes | One pointer |
&[T], &str | 16 bytes | Pointer and length (fat pointer) |
&dyn Trait, Box<dyn Trait> | 16 bytes | Data pointer and vtable pointer |
Vec<T>, String | 24 bytes | Pointer, capacity, length |
Option<Box<T>>, Option<&T> | 8 bytes | None is stored as the null pointer |
Option<&T> costs nothing extra.By default the compiler may reorder struct fields to reduce padding. #[repr(C)] fixes the declared order.
Build settings
[profile.release] opt-level = 3 lto = "fat" codegen-units = 1 panic = "abort"
cargo build --release can be 10 to 100 times faster.Reducing allocations and copies
- Take
&strand&[T]parameters, notStringandVec<T>, when you only read. - Avoid needless
.clone(). Borrow, or share withRc/Arc. - Preallocate with
Vec::with_capacity(n). Cow<'a, str>(clone on write) borrows when it can and allocates only when a change is needed.- Small collections:
SmallVecor arrays avoid the heap.
Static versus dynamic dispatch
Generics are monomorphized and can be inlined, at the price of binary size and compile time. dyn Trait keeps one copy of the code with an indirect call. Choose dyn for cold paths and heterogeneous collections.
Measuring
- Criterion for statistically sound benchmarks; wrap inputs in
std::hint::black_boxso the optimiser does not delete the work. perfandcargo flamegraphto find hot spots.- Iterators let the compiler drop bounds checks that indexed loops keep.
Check yourself
- How large is Option<&T> compared with &T?
- What does a &dyn Trait pointer contain?
- What may the compiler do with struct fields without #[repr(C)]?
- What is Cow<'a, str> useful for?
- Which profile setting enables whole-program optimisation across crates?
- Why use std::hint::black_box in benchmarks?
Advanced Rust concurrency: atomics, lock-free code and variance
Below Mutex and channels, Rust exposes atomics with explicit memory orderings, scoped threads and the interior mutability primitive UnsafeCell. This chapter also covers two type-system topics that matter for such code: variance and higher-ranked lifetimes.
Atomics and memory ordering
use std::sync::atomic::{AtomicUsize, Ordering};
static HITS: AtomicUsize = AtomicUsize::new(0);
HITS.fetch_add(1, Ordering::Relaxed);
let swapped = HITS.compare_exchange(5, 0, Ordering::AcqRel, Ordering::Acquire);| Ordering | Guarantee | Typical use |
|---|---|---|
Relaxed | The operation is atomic, with no ordering relative to other memory | Counters, statistics |
Acquire / Release | A Release store is seen, with everything before it, by an Acquire load | Locks, publishing data |
SeqCst | One global order of all such operations | When in doubt; slowest |
compare_exchange (compare and swap) is the building block of lock-free algorithms: retry in a loop until it succeeds.
Locks in detail
- Poisoning: if a thread panics while holding a
std::sync::Mutex, the mutex is poisoned andlock()returnsErrafterwards. RwLock: many readers or one writer.OnceLockandLazyLock: thread-safe one-time initialisation of globals.
Scoped threads and Rayon
let mut data = vec![1, 2, 3, 4];
std::thread::scope(|s| {
let (left, right) = data.split_at_mut(2);
s.spawn(|| left[0] += 10); // borrows local data: no Arc needed
s.spawn(|| right[0] += 10);
}); // all threads joined hereThe rayon crate turns iter() into par_iter() for data parallelism with work stealing.
UnsafeCell
UnsafeCell<T> is the only legal way to mutate data behind a shared reference. Cell, RefCell, Mutex and atomics are all built on it.Variance
| Type | Variance in T |
|---|---|
&'a T, Box<T>, Vec<T> | Covariant: a longer lifetime can be used where a shorter one is expected |
&'a mut T, Cell<T> | Invariant: the type must match exactly |
fn(T) | Contravariant in its argument |
Invariance of &mut T stops you from storing a short-lived reference into a slot that expects a long-lived one.
Higher-ranked trait bounds
fn apply<F>(f: F) where F: for<'a> Fn(&'a str) -> &'a str { }for<'a> means the closure must work for every lifetime, not one chosen by the caller.
Check yourself
- Which ordering is enough for a simple statistics counter?
- What is mutex poisoning?
- What do scoped threads (std::thread::scope) allow?
- What is UnsafeCell<T>?
- What is the variance of &mut T in T?
- What does for<'a> in a trait bound mean?