gpt4 book ai didi

rust - 向量借用和所有权

转载 作者:行者123 更新时间:2023-12-03 11:26:00 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What does it mean to pass in a vector into a `for` loop versus a reference to a vector?

(1 个回答)



How can I solve "use of moved value" and "which does not implement the `Copy` trait"?

(1 个回答)



What do I have to do to solve a "use of moved value" error?

(3 个回答)



What does "cannot move out of index of" mean?

(1 个回答)


去年关闭。




这不起作用:

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]值应该已移至 largestlargest2然后应该失败,但它没有。

最佳答案

当您使用 vectors里面for..in循环,Rust 将调用 IntoIterator::into_iter Vec的trait方法,它拥有 self 的所有权.因此您不能使用 vectors然后。

use std::iter::IntoIterator;

// these are equivalent
for i in vectors { /* ... */ }
for i in IntoIterator::into_iter(vectors) { /* ... */ }
index operator ,另一方面,调用 Index::index Vec的trait方法,这需要 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);

关于rust - 向量借用和所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61169889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com