1. Threads
use std::thread;
let handle = thread::spawn(|| { println!("child"); });
handle.join().unwrap();
thread::spawntakes an'staticclosure +Sendreturn.moveclosures capture by value so the worker owns access.std::sync::mpscchannels for message passing.
2. Send & Sync
| Marker | Meaning |
|---|---|
Send | type can be moved to another thread safely |
Sync | references to it can be shared across threads |
Rcis not Send/Sync;Arcis.!Sendtypes (Rc,*const T, raw pointers) block moving cross-thread (compile-time).- Proper Send/Sync is checked at compile time.
3. Mutex & Arc
let counter = Arc::new(Mutex::new(0));
let c = Arc::clone(&counter);
thread::spawn(move || {
let mut n = c.lock().unwrap();
*n += 1;
});
Arcshares ownership;Mutexprovides locking;lock()givesMutexGuard.- Poisons on panic:
lock()returnsErrafter a panic inside the guard.
4. async/await — the lightweight model
async fn fetch() -> String {
"ok".to_string()
}
// .await in async context
tokio/async-stdruntime drives futures.async fnreturns a Future;.awaitsuspends, yielding to the runtime.Send + 'staticrequirement when spawning async tasks.
5. Closures
- Closures infer capture: by reference by default,
movefor ownership. Fn/FnMut/FnOncetrait families — how the closure uses captures.- Common in iterators:
.filter(|x| ...),.map(|x| ...).
6. Gotcha sheet — interview fast-refresh
s.len()is bytes, not chars.- Vec growth: index vs
.get(). Stringno linear indexing.Box<dyn Trait>vs generics.Rcin multi-thread;Arcneeded.- Borrow checker fights — share small integers via clones rather than refs.
loopvswhile letvs recursion.- Lifetime
'staticon traits: useBox<dyn Trait + 'static>vs lifetime-bound traits.
7. Interview checkpoint
- Send vs Sync semantics — quick one-liner.
- Rc vs Arc; when Mutex.
- async vs threads — IO-bound vs CPU-bound.
- Closure capture rules; move closure.
- The gotcha sheet — the memory-safe exam favorite.
Premium Content
Unlock Part 5: Concurrency, Closures & Top Gotchas and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans