Rookie Question: &T vs Box<T>

As someone who is not professionally a programmer or officially educated as such, I am about two to three months into learning Rust, and most concepts I have been able to slowly reason my way through. Something I have been stuck on for a while now, though, is the practical difference between using a reference pointer &T versus using the basic smart pointer Box.

I'm probably missing something, but from what I can tell, both are pointers, and so satisfy the need for certain things to of known size at compile time. Both have very similar if not the same dereferencing behavior from the dereferencing operator. Both can, themselves, be referenced. I believe both are stored on the stack.

Even one of the examples I've seen of using Box for recursive types, something along the lines of:

struct Recursive<T> {
content: T,
child: Box<Recursive<T>>,
}

seems to be identically achievable using the & pointer:

struct Recursive<'a, T> {
content: T,
child: &'a Recursive<'a, T>,
}

I would like to understand where the functional differences are, but I'm having trouble getting it through my skull with just the documentation.

There's a number of differences; I've listed some below. The biggest difference is ownership. Some of the other differences could be viewed as following from the ownership difference.

Ownership difference

Box<T> owns the T -- when the Box<_> gets dropped (goes out of scope for example), or is overwritten, the T also gets dropped. This is similar to how when a struct value drops, all the values in its fields also drop.

In contrast, &'a T is borrowing the T, for some duration 'a. It does not drop T. Not only does a &T not own the T, but a &T implements Copy. You can create as many copies of the reference as you like. None of them own the T. They are all shared borrows of the T.

This is a very big difference. Ownership and borrows is a large topic in Rust.

If you try to use &T when you need ownership,[1] you will run into borrow checker errors like crazy. Generally speaking, &T is for short lived borrows, not long lived data structures.

Immutability difference

The place a &T points to is immutable (unless there's an intermediate UnsafeCell). You can't take a &mut *ref_t or soundly transmute the &T to a &mut T. You can't overwrite *ref_t.

The place a Box<T> points to can be overwritten and otherwise mutated. You can take a &mut *box_t and overwrite *box_t.

There may also be other exclusivity concerns with Box<T>, similar to how there are for &mut T. (As the link says, it's still an area of development.)

Moving the referent difference

You cannot move a T from underneath a &T. (You can clone the T if it supports cloning, and you can copy the T if the type is Copy, but you cannot move the T.)

You can move Ts in and out of a Box<T>, leaving it partially uninitialized for a time, similar to how you can move fields out of nominal structs. This is to date a special ability of Box.

Reliance on an allocator and the heap guarantee differences

Box<T> is partially a library type. It requires the alloc crate.[2] Box<T> guarantees that T is allocated on the heap[3] (unless T has size 0). So creating a Box<T> allocates heap memory, where the T is stored.

&T is a primitive type, part of the Rust language. It's not dependent on any part of the std library. Creating &T does not allocate heap memory. You reference the address of a T that exists elsewhere. And that could be anywhere, not just the heap.

An aside about the stack

There isn't really such a thing as an "[only] on the stack type"; there are inline values, and there are values behind indirection. The inline value of both &T and of Box<T> is a pointer.[4] Which means that pointer is on the stack if it's in a local variable...[5] but on the heap if it's in a Vec<_>, or it could be in a static, etc. Rust types don't intrinsically "care" where values of that type are stored.

Box<T>'s guarantee to put T on the heap is a library level guarantee, not something intrinsic in the language.[6]


  1. be it T or Box<T> or Rc<T> or something else ↩︎

  2. It is also a "magic" type with built-in compiler support in some ways, but some have a long term goal to make it implementable purely as a library type. ↩︎

  3. or the equivalent of a heap for a given global allocator ↩︎

  4. If T is not Sized, it's a pointer and some other metadata, like a dyn vtable pointer or a [_] length. ↩︎

  5. notionally! Maybe it's optimized to be in a register or optimized away entirely ↩︎

  6. In certain cases -- say, you never observe the address of the T -- even Box's (or Vec's, etc) heap allocation may be optimized away. ↩︎

There's two distinctions to make note of here. The first distinction is between having the value inline and having the value behind a pointer. The second distinction is between owning the value and borrowing the value.

  • T: inline, owned
  • &T: behind pointer, borrowed
  • Box<T>: behind pointer, owned
  • I don't know of any construct in rust for inline borrowed values.

I'd say that the more important distinction here is the owning-borrowing distinction. Although &T and Box<T> have the same representation, in practice you're going to treat Box<T> as being more similar to T when it comes to actually working with it. Box<T> is roughly for situations where you'd like to use T, but having T be inline wouldn't work (for example, because T doesn't have a compile-time known size, or because you can't embed a type inline inside itself), or would be suboptimal (for example, storing T inline would cause a type to take up a lot of space), so you put it behind a pointer instead.

I appreciate both answers, the distinction of ownership makes much more sense. So if I am understanding, to use the example of a recursive struct with a 'child' field:

A struct using a &T pointer would be able to exist, however when when a parent node is dropped, because the node didn't have ownership of the child node, the child node wouldn't automatically drop. As well, even if the child node could be mutated via making the reference an &mut reference (somehow, not sure if that's possible or advisable), the ownership of the child node couldn't be moved out from the parent node, because the parent node never owned the child node.

Meanwhile, with the same struct using a Box<T> pointer for the child node, the child node drops when the parent node drops, can be mutable from the parent node, and can have its ownership passed by the parent node to another scope.

Is that more or less correct?

This is true but perhaps misleading. It is not the case that dropping T will be neglected. The responsibility to drop the T lies with the T’s owner, not with the &T or a struct owning the &T, because &T is a borrower, not an owner. Under normal circumstances, the T will be dropped, later, by its actual owner, after the &T no longer exists.

It’s possible, but should only be done in particular circumstances. In general, defining structs containing references (whether mutable or not) is uncommon; it makes those structs themselves temporary borrowers in the same way the references are, and limits how the structs can be used.

This is false. std::mem::swap(), and its siblings take and replace, can be used to move a value out from a &mut T, as long as you put another T value in place. This is especially flexible when you have &mut Option<T> (such as you might when manipulating a tree structure), since the replacement can then be None.

I wrote some stuff in the Rust Playground that can hopefully help illustrate things a bit.

On when things drop:

On what you can and can't do with things (note that some of the &* and &mut * can be replaced with just & and &mut, potentially also needing let to be replaced by let mut, for somewhat complicated reasons that I'm not thoroughly an expert in):

There's some further complications from the way that let mut works, the fact that you apparently can't directly move fields out of types if they implement Drop (that's why I needed two separate playground links), and functions like std::mem::swap as kpreid mentioned, but broadly speaking:

  • T and Box<T> have one behaviour when it comes to dropping (the parent and child drop together), and &T and &mut T have another (the child does not drop with the parent -- it drops at some later time).
  • T and Box<T> can be directly read, written to, and moved out of; &mut T only directly read and written to; &T only directly read.

I'd also second the comment that you'd mostly stick with owned types in structs (T, Box<T>, Vec<T>, String), and use &T and &mut T a lot more rarely.

Thank you! That code is a very helpful side-by-side comparison.