Why is iterating over a collection via `for` loop considered a “move” in Rust?

前端 未结 1 1943
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 00:54

I have the below Rust program.

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

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


        
相关标签:
1条回答
  • 2020-12-12 01:19

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

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

    Vec implements IntoIterator, allowing you to own a Vec instance’s elements by consuming it:

    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.

    (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.)

    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.

    0 讨论(0)
提交回复
热议问题