向量借用和所有权[重复]

2024-01-30

这不起作用:

let vectors = vec![1, 2, 3, 4, 5, 6, 7];

for i in vectors {
    println!("Element is {}", i);
}

let largest = vectors[0];

错误信息:

error[E0382]: borrow of moved value: `vectors`
 --> src/main.rs:8:19
  |
2 |     let vectors = vec![1, 2, 3, 4, 5, 6, 7];
  |         ------- move occurs because `vectors` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
3 | 
4 |     for i in vectors {
  |              -------
  |              |
  |              value moved here
  |              help: consider borrowing to avoid moving into the for loop: `&vectors`
...
8 |     let largest = vectors[0];
  |                   ^^^^^^^ value borrowed here after move

该向量已移至循环中。它的所有权及其各个元素的所有权已永久转移到那里。

但这有效:

let largest = vectors[0];
let largest2 = vectors[0];

我不知道为什么;这vectors[0]值应该已移至largest and largest2然后应该会失败,但事实并非如此。


当你使用vectors里面一个for..in循环,Rust 会调用IntoIterator::into_iter https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#tymethod.into_iter的特征方法Vec,它拥有self。因此你不能使用vectors然后。

use std::iter::IntoIterator;

// these are equivalent
for i in vectors { /* ... */ }
for i in IntoIterator::into_iter(vectors) { /* ... */ }

The 索引运算符 https://doc.rust-lang.org/std/ops/trait.Index.html,另一方面,称为Index::index https://doc.rust-lang.org/std/ops/trait.Index.html#tymethod.index的特征方法Vec,这需要self引用。此外,它会自动取消引用该值,因此如果向量内的项目实现Copy,它们将从向量中复制出来而不是借用(如果需要引用,则需要显式借用):

use std::ops::Index;

// these are equivalent
let x = vectors[0];
let x = *Index::index(&vectors, 0);

// these are equivalent
let x = &vectors[0];
let x = Index::index(&vectors, 0);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

向量借用和所有权[重复] 的相关文章

随机推荐