Rust vector iteration

less than 1 minute read

The following example shows difference of iterating vector items between for and with iter() method

1
2
3
4
let vs = vec![1, 2, 3];
for (v : vs) {
  // consumes v, owned v
}
1
2
3
4
let vs = vec![1, 2, 3];
for (v : &vs) {
  // borrows vs, & v
}
1
2
3
4
let vs = vec![1, 2, 3];
for (v : vs.iter()) {
  // this is equivalent to for (v: &vs)
}
1
2
3
4
let vs = vec![1, 2, 3];
for (v : vs.into_iter()) {
  // this is equivalent to for (v: vs)
}

Categories:

Updated: