0

Is there any difference in the following approaches to iterate through a vector? Both methods successfully iterate.

let vo = vec![30, 50, 70, 80];

Method 1

for uu in vo.iter() {
    println!("uu {}", uu);
}
println!("vo 1 {:?}", vo);

Method 2

for uu in &vo {
    println!("{}", uu);
}
println!("vo 2 {:?}", vo);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Hendry Lim
  • 1,929
  • 2
  • 21
  • 45
  • See also: https://stackoverflow.com/questions/43036279/what-does-it-mean-to-pass-in-a-vector-into-a-for-loop-versus-a-reference-to-a – E_net4 Jun 16 '20 at 14:12

1 Answers1

1

No difference, no.

The second one is impl<'a, T> IntoIterator for &'a Vec<T>, and it just call the first one (Vec::iter). Since the method is so short, there's roughly 100% chances it's going to get inlined and you'll get the same result (with an intermediate function call if you're compiling without optimisations but that's about it).

Masklinn
  • 34,759
  • 3
  • 38
  • 57