1. Traits — Rust’s interfaces
- A trait bundles methods; types implement it.
trait Speak { fn speak(&self); }
struct Dog;
impl Speak for Dog {
fn speak(&self) { println!("woof"); }
}
- Default methods allowed;
derivegenerates common ones (Debug,Clone,PartialEq).
2. Generic functions & trait bounds
fn largest<T: PartialOrd>(list: &[T]) -> &T {
&list[0]
}
T: Bound= bound;where T: Boundfor clearer long bounds.- Generics compile to monomorphized code per concrete type — no runtime cost, but code bloat.
3. Deref, Box, Rc, Arc, RefCell
| Type | Purpose |
|---|---|
Box<T> | sole-ownership heap allocation, Deref to T |
Rc<T> | single-thread ref-counted sharing |
Arc<T> | multi-thread Send + Sync ref-counting |
RefCell<T> | interior mutability — borrow-check at runtime |
Rc::clone(&rc)increments count (not the value).RefCellborrow panics at runtime if rules violated — “borrow already exists”.
let a = Rc::new(5);
let b = Rc::clone(&a); // count 2
4. Trait objects (dyn Trait)
&dyn Trait/Box<dyn Trait>— dynamically dispatched (pointer to method via vtable).- Requires object-safe traits (no generic methods).
Box<dyn Error>is the classic error-erasing pattern.
5. Cow, From/Into, Deref
Derefcoercion:&String→&strautomatically.impl From<T>/.into()conversion pairs.Cow= copy-on-write — borrows until mutated.
6. Interview checkpoint
- Trait vs generics vs trait objects.
- Rc vs Arc — thread safety; RefCell interior mutability.
- Box for recursion (sized type requirement).
- Object safety vs generics.
- Deref coercion rules.
Premium Content
Unlock Part 3: Traits, Generics & Smart Pointers and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans