矢量索引时是什么操作(不带&)

Rij*_*jul 5 rust

根据 rust book(矢量部分 - Ch-8.1)

let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0]; // <-- This is an immutable borrow
v.push(6); // Which is why push() operation is not allowed (since this is a mutable borrow)
println!("The first element is: {}", first);
Run Code Online (Sandbox Code Playgroud)

因为&v[0]是不可变的借用,所以v.push(100)操作不应该起作用。这是有道理的。

然而,这有效:

let mut v = vec![1, 2, 3, 4, 5];
let first = v[0];
v.push(6);
println!("The first element is: {}", first);
Run Code Online (Sandbox Code Playgroud)

&从 中删除时v[0]push()操作工作正常。

问题):

  1. 如果添加&创建引用(并且不移动所有权),这是否意味着删除后&,所有权v[0]转移到变量first?如果是这样,我之后就可以访问v[0]。这是为什么?
  2. 如果(1)不是这种情况,这是一个Copy操作吗?即存储在内存位置的值v[0]被复制到变量first
  3. 如果不是(2),那么这里到底发生了什么?

Cha*_*man 8

是的,这是一个副本,因为没有&它的移动,移动i32就是复制它,因为它实现了该Copy特征(此外,您不能移出索引,所以这必须是一个副本)。

编辑:正如@prog-fh在评论中所建议的,如果您使用非Copy类型,编译器会告诉您:

struct NoCopy;
let mut v = vec![NoCopy];
let _first = v[0];
Run Code Online (Sandbox Code Playgroud)
error[E0507]: cannot move out of index of `Vec<NoCopy>`
 --> src/main.rs:4:18
  |
4 |     let _first = v[0];
  |                  ^^^^
  |                  |
  |                  move occurs because value has type `NoCopy`, which does not implement the `Copy` trait
  |                  help: consider borrowing here: `&v[0]`

For more information about this error, try `rustc --explain E0507`.
Run Code Online (Sandbox Code Playgroud)

游乐场