What is the difference between Vec<i32> and Vec<Box<i32>>?

I'll draw a diagram. The first value is a pointer to a contiguous array of numbers on the heap.

(stack)    (heap)
┌──────┐   ┌───┐
│ vec1 │──→│ 1 │
└──────┘   ├───┤
           │ 2 │
           ├───┤
           │ 3 │
           ├───┤
           │ 4 │
           └───┘

The second version adds extra indirection. The elements are still on the heap, but now they're somewhere else on the heap.

(stack)    (heap)   ┌───┐
┌──────┐   ┌───┐ ┌─→│ 1 │
│ vec2 │──→│   │─┘  └───┘
└──────┘   ├───┤    ┌───┐
           │   │───→│ 2 │
           ├───┤    └───┘
           │   │─┐  ┌───┐
           ├───┤ └─→│ 3 │
           │   │─┐  └───┘
           └───┘ │  ┌───┐
                 └─→│ 4 │
                    └───┘

Due to the way ownership works in Rust, you are not going to run into any semantic differences. The extra indirection gives you worse memory usage and cache locality.


vec![1, 2, 3, 4] is a vector of i32s.

vec![Box::new(1), Box::new(2), Box::new(3), Box::new(4)] is a vector of owned pointers to i32s. Rust's owned pointer is similar to C++'s unique_ptr.

Tags:

Rust