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?
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.
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.
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] .
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();
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 i32
s.
vec![Box::new(1), Box::new(2), Box::new(3), Box::new(4)]
is a vector of owned pointers to i32
s. Rust's owned pointer is similar to C++'s unique_ptr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With