Difference between iter () and in_iter () on a shared, borrowed Vec?

I read the Rust 101 tutorial, where the author talks about co-borrowing with an example of a Vec object passed to a function. Below is a small MWE adaptation of what the tutorial teaches. The interesting part is v.iter() in vec_min . The author writes:

This time we explicitly request an iterator for the vector v . The iter method borrows the vector it runs on and exposes the common roles of the elements.

But what happens if I use the for ... in ... construct for ... in ... shared object? According to this blog post , this implicit loop uses into_iter() , taking responsibility v . But he cannot take responsibility for v in this function, since he only borrowed it for a start, right?

Can someone explain the difference between into_iter() and iter() in relation to a borrowed object for me?

 enum NumberOrNothing { Number(i32), Nothing, } use self::NumberOrNothing::{Number,Nothing}; impl NumberOrNothing { fn print(self) { match self { Nothing => println!("The number is: <nothing>"), Number(n) => println!("The number is: {}", n), }; } } fn vec_min(v: &Vec<i32>) -> NumberOrNothing { fn min_i32(a: i32, b: i32) -> i32 { if a < b {a} else {b} } let mut min = Nothing; for e in v.iter() { //Alternatively implicitly and with *e replaced by e: //for e in v { min = Number(match min { Nothing => *e, Number(n) => min_i32(n, *e), }); } min } pub fn main() { let vec = vec![18,5,7,2,9,27]; let foo = Nothing; let min = vec_min(&vec); let min = vec_min(&vec); min.print(); } 
+6
source share
1 answer

But he cannot really take on the role of v in this function, since he borrowed it only from

Absolutely you can take responsibility v , because it is a &Vec . Pay attention to the exact semantics here - you take on the role of the link, not the element mentioned.

If you look at the IntoIterator developers , you can find:

 impl<'a, T> IntoIterator for &'a Vec<T> 

And the source for this :

 impl<'a, T> IntoIterator for &'a Vec<T> { fn into_iter(self) -> slice::Iter<'a, T> { self.iter() } } 

Surprise - he calls iter ! Therefore, the answer to your question: there is no difference.

+9
source

All Articles