Vec i32 和Vec i32 有什么区别?和Vec<Box<i32>? [英] What is the difference between Vec&lt;i32&gt; and Vec&lt;Box&lt;i32&gt;&gt;?

查看:64
本文介绍了Vec i32 和Vec i32 有什么区别?和Vec<Box<i32>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

它们之间有什么区别?我已经在堆上分配了 vec1.那么 vec1 的所有元素不都在堆上吗?为什么我需要像在 vec2 中那样在堆上单独分配它们?

解决方案

我会画一个图表.第一个值是指向堆上连续数字数组的指针.

<前>(堆栈)(堆)┌──────┐ ┌────┐│ vec1 │──→│ 1 │└──────┘ ├───┤│ 2 │├────┤│ 3 │├────┤│ 4 │└────┘

第二个版本增加了额外的间接性.元素仍然在堆上,但现在它们在堆上其他地方.

<前>(栈) (堆) ┌───┐┌──────┐ ┌───┐ ┌─→│ 1 ││ vec2 │──→│ │─┘ └───┘└──────┘ ├───┤ ┌───┐│ │───→│ 2 │├───┤ └───┘│ │─┐ ┌───┐├───┤ └─→│ 3 ││ │─┐ └───┘└───┘│ ┌───┐└─→│ 4 │└────┘

由于所有权在 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?

解决方案

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 i32 和Vec i32 有什么区别?和Vec<Box<i32>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆