Smart pointers in Rust

In the post above, I mentioned the Vec is a ownership pointer that has three members.

In Rust, pointer-like stuffs which has internal special metadata are called smart pointers.

Smart pointers in Rust are such as:

  • Heap management: Box
  • Reference counting: Rc, Weak, Arc
  • Guard: Ref, RefMut, MutexGuard, RwLockReadGuard, RwLockWriteGuard

The special thing about smart pointers is that hey have special metadata and special Drop implementation and Deref and DerefMut implementations (if posssble) for ergonomics.

For example, MutexGuard's Drop unlocks the lock structure in the internal metadata.

impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
    fn drop(&mut self) {
        unsafe {

If you have a C++ programmer, you can find this is the same in C++.

void safe_increment()
    std::lock_guard<std::mutex> lock(g_i_mutex);
    std::cout << std::this_thread::get_id() << ": " << g_i << '\n';
    // g_i_mutex is automatically released when lock
    // goes out of scope

And yes, Rust just generalizes the idea into language level by defining traits.

Smart pointers in C++ are such as

  • unique_ptr
  • shared_ptr
  • weak_ptr

and they are counterparts of Box, Rc and Weak in Rust. This is also a generalization of separate concepts in C++ into a single concept called small pointers in Rust.