gpt4 book ai didi

rust - 为什么通过 `for` 循环迭代集合在 Rust 中被认为是 "move"?

转载 作者:行者123 更新时间:2023-12-03 11:24:01 28 4
gpt4 key购买 nike

我有以下 Rust 程序。

fn main() {
let v = vec![100, 32, 57];
for i in v {
println!("{}", i);
}

println!("{:?}", v);
}

当我运行它时,我得到:

error[E0382]: borrow of moved value: `v`
--> src\main.rs:7:22
|
2 | let v = vec![100, 32, 57];
| - move occurs because `v` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
3 | for i in v {
| -
| |
| value moved here
| help: consider borrowing to avoid moving into the for loop: `&v`
...
7 | println!("{:?}", v);
| ^ value borrowed here after move

错误指出在 for i in v 处发生了 move 。 .但我只是使用相同的变量 vlet v = vec![100, 32, 57] 定义.它不像 let v2 = v; for i in v2 ... ,将值从 v move 至 v2 .谁能帮忙解释一下?

最佳答案

https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops说,

A for expression is a syntactic construct for looping over elements provided by an implementation of std::iter::IntoIterator.

Vec implements IntoIterator ,让您拥有一个 Vec通过消费实例的元素:

Creates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this.


(如错误消息所述,解决此问题的方法是循环遍历 &v 而不是 v ,借用其元素而不是拥有它们。您可以循环 for &i in &v 以维护 i 的类型。)
从高层次上讲,您似乎没有必要拥有 v 的元素。 ,因为它们是可复制的,但没有特殊的实现允许在此处使用该信息。 IntoIterator.into_iter()需要 self ,这意味着 for 循环总是消耗被迭代的值。

关于rust - 为什么通过 `for` 循环迭代集合在 Rust 中被认为是 "move"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123462/

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