存储Vec与切片之间有什么区别? [英] What is the difference between storing a Vec vs a Slice?

查看:94
本文介绍了存储Vec与切片之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 call Bar::new(vec![1, 2, 3, 4, 5])?
  • Will the contents of Vec be implicitly destroyed when the owner Bar 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由三部分组成:

  1. 指向大块内存的指针
  2. 分配多少内存(容量)
  3. 存储多少个项目的计数(大小)
  1. A pointer to a chunk of memory
  2. A count of how much memory is allocated (the capacity)
  3. A count of how many items are stored (the size)

切片由两部分组成:

  1. 指向大块内存的指针
  2. 存储多少个项目的计数(大小)

无论您何时移动其中任何一个,这些字段都将被复制.您可能会猜到,那是相当轻巧的.堆上的实际内存块将不会被复制或移动.

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屋!

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