0

In Chapter 8 of the Rust Book they give they following example:

let v = vec![100, 32, 57];
for i in &v {
    println!("{}", i);
}

I don't understand why &v was used instead of v.

If v is immutable what is the purpose of using a reference instead of v itself?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
  • 1
    I'm not a rust developer but I'm guessing that without the reference notation (`&`) the program will try to copy `v`? – David Haim May 28 '18 at 21:05
  • 4
    No, Rust will not automatically copy most types, including a `Vec`. The value would be moved and no longer available. – Shepmaster May 28 '18 at 21:24
  • @Shepmaster I didn't realize a for loop would take ownership like that. I (incorrectly) assumed it would behave like `if s == "str"` or `println!("{}", s)` which do not appear to take ownership. – Increasingly Idiotic May 28 '18 at 23:59
  • 2
    Certainly. However, [`PartialEq` takes `&self`](https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#tymethod.eq) and [`println!` is a macro and takes its arguments by reference for usability](https://stackoverflow.com/questions/30450399/does-println-borrow-or-own-the-variable). – Shepmaster May 29 '18 at 01:20

0 Answers0