Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 3: Traits, Generics & Smart Pointers
RUST

Part 3: Traits, Generics & Smart Pointers

Master Rust traits, generics, trait objects, Box, Rc, Arc, and the ownership patterns behind smart pointers.

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; derive generates common ones (Debug, Clone, PartialEq).

2. Generic functions & trait bounds

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    &list[0]
}
  • T: Bound = bound; where T: Bound for clearer long bounds.
  • Generics compile to monomorphized code per concrete type — no runtime cost, but code bloat.

3. Deref, Box, Rc, Arc, RefCell

TypePurpose
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).
  • RefCell borrow 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

  • Deref coercion: &String&str automatically.
  • 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.

My Private Notes

Notes are auto-saved locally to this device.