Programming Languages Rust Subjective
Oct 04, 2025

What are smart pointers in Rust and when would you use each type?

Detailed Explanation
Smart pointers in Rust: • Box: Heap allocation for single ownership • Rc: Reference counting for shared ownership (single-threaded) • Arc: Atomic reference counting (thread-safe) • RefCell: Interior mutability with runtime borrow checking • Mutex: Thread-safe interior mutability • Weak: Non-owning references to break cycles When to use each: • Box: Large data, recursive types, trait objects • Rc: Multiple owners in single-threaded code • Arc: Multiple owners across threads • RefCell: Mutate through immutable references • Mutex: Shared mutable state across threads Example: use std::rc::Rc; use std::cell::RefCell; // Shared ownership with interior mutability let data = Rc::new(RefCell::new(vec![1, 2, 3])); let data1 = Rc::clone(&data); let data2 = Rc::clone(&data); data.borrow_mut().push(4); println!("{:?}", data1.borrow()); // [1, 2, 3, 4] // Recursive type with Box enum List { Cons(i32, Box), Nil, } let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback