问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/21066133/what-is-the-difference-between-veci32-and-vecboxi32