11
let vec1 = vec![1, 2, 3, 4];
let vec2 = vec![Box::new(1), Box::new(2), Box::new(3), Box::new(4)];

What is the difference between them? I have already allocated vec1 on the heap. So aren't all the elements of vec1 also on the heap? Why would I need to separately allocate them on the heap like in vec2?

oli_obk
  • 28,729
  • 6
  • 82
  • 98
sunny1304
  • 1,684
  • 3
  • 17
  • 30
  • 2
    Not a rust expert here, but I think the difference is that `1` is the value 1, while `~1` is a owned pointer to 1. So in `vec2` you're just getting one more level of indirection – Paolo Falabella Jan 11 '14 at 19:01

2 Answers2

32

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.

oli_obk
  • 28,729
  • 6
  • 82
  • 98
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
4

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.

oli_obk
  • 28,729
  • 6
  • 82
  • 98
A.B.
  • 15,364
  • 3
  • 61
  • 64