0

I'm learning about ownership and borrowing.

The difference between borrow1 and borrow2 is the usage of & while printing in borrow2:

fn borrow1(v: &Vec<i32>) {
    println!("{}", &v[10] + &v[12]);
}

fn borrow2(v: &Vec<i32>) {
    println!("{}", v[10] + v[12]);
}

fn main() {
    let mut v = Vec::new();

    for i in 1..1000 {
        v.push(i);
    }

    borrow1(&v);
    println!("still own v {} , {}", v[0], v[1]);

    borrow2(&v);
    println!("still own v {} , {}", v[0], v[1]);
}

Why do they give the same output, even though borrow1 doesn't have &?

user51
  • 8,843
  • 21
  • 79
  • 158

1 Answers1

4

The index operator ([]) for a Vec<T> returns a T. In this case, that's an i32. Thus v[0] returns an i32 and &v[0] returns an &i32:

let a: i32 = v[0];
let b: &i32 = &v[0];

v[0] only works because i32 implements Copy.

i32 has implemented Add for both the (left-hand side, right-hand-side) pairs of (i32, i32) and (&i32, &i32). The two implementations add values in the same way, so you get the same result.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366