Why can I iterate over a slice twice, but not a vector?

前端 未结 1 1165
长发绾君心
长发绾君心 2020-12-01 23:58

If I try to iterate over a slice twice, it works fine:

let a = &[1, 2, 3];
for i in a {
    println!(\"{}\", i);
}
for i in a {            // works fine
         


        
1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 00:03

    Like you said, for works by taking the thing you asked it to iterate over, and passing it through IntoIterator::into_iter to produce the actual iterator value. Also as you said, into_iter takes the subject by value.

    So, when you try to iterate over a Vector directly, this means you pass the entire vector, by value, into its IntoIterator implementation, thus consuming the vector in the process. Which is why you can't iterate over a vector directly twice: iterating over it the first time consumes it, after which it no longer exists.

    However, slices are different: a slice is an immutable, borrowed pointer to its data; immutable, borrowed pointers can be copied freely. This means that the IntoIterator for immutable slices just borrows the data and doesn't consume it (not that it could). Or, to look at it another way, its IntoIterator implementation is simply taking a copy of the slice, whereas you can't copy a Vec.

    It should be noted that you can iterate over a Vec without consuming it by iterating over a borrow. If you check the documentation for Vec, you'll note that it lists implementations of IntoIterator for Vec, &Vec and &mut Vec.

    let mut a: Vec = vec![1, 2, 3];
    
    for i in &a {           // iterate immutably
        let i: &i32 = i;    // elements are immutable pointers
        println!("{}", i);
    }
    
    for i in &mut a {       // iterate mutably
        let i: &mut i32 = i;// elements are mutable pointers
        *i *= 2;
    }
    
    for i in a {            // iterate by-value
        let i: i32 = i;     // elements are values
        println!("{}", i);
    }
    
    // `a` no longer exists; it was consumed by the previous loop.
    

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