存储Vec与切片之间有什么区别? [英] What is the difference between storing a Vec vs a Slice?
问题描述
Rust提供了几种在用户定义的结构内存储元素集合的方法.可以给该结构一个自定义的生存期说明符,以及对切片的引用:
Rust provides a few ways to store a collection of elements inside a user-defined struct. The struct can be given a custom lifetime specifier, and a reference to a slice:
struct Foo<'a> {
elements: &'a [i32]
}
impl<'a> Foo<'a> {
fn new(elements: &'a [i32]) -> Foo<'a> {
Foo { elements: elements }
}
}
或者可以给它一个Vec
对象:
Or it can be given a Vec
object:
struct Bar {
elements: Vec<i32>
}
impl Bar {
fn new(elements: Vec<i32>) -> Bar {
Bar { elements: elements }
}
}
这两种方法之间的主要区别是什么?
What are the major differences between these two approaches?
- 每当我调用
Bar::new(vec![1, 2, 3, 4, 5])
时,会使用Vec
强制该语言复制内存吗? - 当所有者
Bar
超出范围时,是否会隐式销毁Vec
的内容? - 如果切片在要传递给的结构之外使用,是否有通过引用传递切片的危险?
- Will using a
Vec
force the language to copy memory whenever I callBar::new(vec![1, 2, 3, 4, 5])
? - Will the contents of
Vec
be implicitly destroyed when the ownerBar
goes out of scope? - Are there any dangers associated with passing a slice in by reference if it's used outside of the struct that it's being passed to?
推荐答案
Vec
由三部分组成:
- 指向大块内存的指针
- 分配多少内存(容量)
- 存储多少个项目的计数(大小)
- A pointer to a chunk of memory
- A count of how much memory is allocated (the capacity)
- A count of how many items are stored (the size)
切片由两部分组成:
- 指向大块内存的指针
- 存储多少个项目的计数(大小)
无论您何时移动其中任何一个,这些字段都将被复制.您可能会猜到,那是相当轻巧的.堆上的实际内存块将不会被复制或移动.
Whenever you move either of these, those fields are all that will be copied. As you might guess, that's pretty lightweight. The actual chunk of memory on the heap will not be copied or moved.
A Vec
表示内存的所有权,而分片表示内存的借用.当Vec
本身被释放时,需要重新分配所有项和内存块(在Rust来说,是 dropped ).当它超出范围时,就会发生这种情况.切片放下后什么也不做.
A Vec
indicates ownership of the memory, and a slice indicates a borrow of memory. A Vec
needs to deallocate all the items and the chunk of memory when it is itself deallocated (dropped in Rust-speak). This happens when it goes out of scope. The slice does nothing when it is dropped.
使用切片没有任何危险,因为这是Rust lifetimes 的处理方式.这些可以确保您从不使用引用后将其无效.
There are no dangers of using slices, as that is what Rust lifetimes handle. These make sure that you never use a reference after it would be invalidated.
这篇关于存储Vec与切片之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!