Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 639
sunny1304 Avatar asked Jan 11 '14 18:01

sunny1304


People also ask

What is VEC Rust?

Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take O(1) complexity.

What is box in Rust?

All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box<T> . A box is a smart pointer to a heap allocated value of type T . When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.

How do you pass a vector reference in Rust?

Use primeFactors. as_slice() (or primeFactors. as_mut_slice() if you want to modify the contents of the vector in place) to pass a vector as a borrowed pointer. Change your function to accept a borrowed slice of type &[T] .

How do you initialize VEC in Rust?

In Rust, there are several ways to initialize a vector. In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new();


2 Answers

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.

like image 154
Dietrich Epp Avatar answered Nov 16 '22 08:11

Dietrich Epp


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.

like image 28
A.B. Avatar answered Nov 16 '22 07:11

A.B.