为什么通过“ for”循环遍历一个集合被认为是“移动”过程。在Rust中? [英] Why is iterating over a collection via `for` loop considered a "move" in Rust?

查看:217
本文介绍了为什么通过“ for”循环遍历一个集合被认为是“移动”过程。在Rust中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Rust程序。

I have the below Rust program.

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

移动后在此处借入的^错误错误指出存在移动发生在v中的 for i 。但是我只是使用 let v = vec![100,32,57] 定义的相同变量 v 。它不像 let v2 = v;对于v2中的i ... ,它将值从 v 移到了 v2 。有人可以帮忙解释一下吗?

The error states that there is a move happened at for i in v. But I'm just using the same variable v defined by let v = vec![100, 32, 57]. It's not something like let v2 = v; for i in v2 ..., which moved the value from v to v2. Could anyone help to explain a little bit?

推荐答案

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


用于表达式的是用于循环提供的元素的语法构造通过 std :: iter :: IntoIterator 的实现。

Vec 实现 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.

(如错误消息所述,解决此问题的方法是在<$上循环c $ c>& v 而不是 v ,而是借用其元素而不是拥有它们。您可以为&循环 ; i在& v 中保持 i 的类型。)

(As the error message notes, the way to fix this is to loop over &v instead of v, borrowing its elements instead of owning them. You can loop for &i in &v to maintain the type of i.)

它对于您来说,拥有 v 的元素似乎是不必要的,因为它们是可复制的,但是没有特殊的实现允许这样做。 IntoIterator.into_iter()接受 self ,这意味着for循环始终消耗要迭代的值。

It might seem unnecessary at a high level for you to own the elements of v, since they’re copyable, but there’s no special implementation allowing for that. IntoIterator.into_iter() takes self, meaning a for loop always consumes the value being iterated over.

这篇关于为什么通过“ for”循环遍历一个集合被认为是“移动”过程。在Rust中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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