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(); }
source share