Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use smart pointers?

There is a similar, very popular question for C++, but I couldn't find a similar existing question for Rust.

So, what are the use cases for Box, Rc, Ref, RefMut (others?) in Rust?

The important part of the question (for me personally): when should smart pointers be used instead of references?

I know The Rust Book explains it very, very thoroughly, but I wish there would be a succinct and quick "cheatsheet" on the subject, possibly with some real-world examples that are missing in the book.

like image 871
Nurbol Alpysbayev Avatar asked Mar 27 '26 15:03

Nurbol Alpysbayev


1 Answers

What are the use cases for Box, Rc, Ref, RefMut (others?) in Rust?

Okay, here we go:

  • Box, in the simplest terms, is used when you have an object you want to keep on the heap. Use a box when
    • You want to own a dynamically sized object
    • You want to leak an object into 'static lifetime
    • You want to produce an ffi pointer
    • You want to make recursive types
  • Rc is used when it is very difficult to decide on the lifetimes of objects. It's a sign of laziness to overuse, and somewhat defeats the purpose of lifetimes.
  • Ref and RefMut are the objects produced by a RefCell when you try to get access to its contents. A RefCell will track the borrowing state of its object at runtime instead of compile time, so it is kind of like lifetimes. A general use for this is when you need to have mutable references to many objects in a hashmap for example.
  • Arc is used with either RwLock (Essentially the same as RefCell apart from what's below) or Mutex when trying to share an object across a thread boundary. The examples on their pages will show you how to use them and why they are important as opposed to using the Rc<RefCell<T>> pattern.

There are a few more "smart" pointers per se in rust, but what you must know is that everything will eventually de-allocate its contents unless you've used unsafe code or used the global allocator directly.

This ties into why the tools built into the language (lifetimes) are so important to Rust, they accomplish all that Rc and RefCell accomplish but without the performance drawbacks and also do what C/C++ do without the chance of UB.

like image 103
Optimistic Peach Avatar answered Mar 29 '26 05:03

Optimistic Peach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!