0

As far as I know, the & symbol creates a reference. But using sum_vec with or without & will both compile. I just want to know what is happening when I do let s1 = sum_vec(&v1);. will this create a reference of a reference ?

fn main() {
    // Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed.
    fn sum_vec(v: &Vec<i32>) -> i32 {
        return v.iter().fold(0, |a, &b| a + b);
    }
    // Borrow two vectors and sum them.
    // This kind of borrowing does not allow mutation to the borrowed.
    fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
        // do stuff with v1 and v2
        let s1 = sum_vec(v1);//This wil also complile with &. Is this optional?.
        let s2 = sum_vec(v2);
        // return the answer
        s1 + s2
    }

    let v1 = vec![1, 2, 3];
    let v2 = vec![4, 5, 6];

    let answer = foo(&v1, &v2);
    println!("{}", answer);
    println!("{}", v1.len());
}

(playground)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Pepernoot
  • 3,409
  • 3
  • 21
  • 46
  • 1
    Note: it is more idiomatic (and flexible) to take a `&[T]` argument rather than a `&Vec` argument. The only difference between a `Vec` and slice is that the latter, when mutable, allows adding/removing elements. Since when immutable there is no difference, using the lowest common denominator allows more code to call into the function. – Matthieu M. Nov 11 '16 at 08:49
  • @MatthieuM. It's like we [made a question](http://stackoverflow.com/q/40006219/155423) so we didn't have to repeat that all the time ^_^ – Shepmaster Nov 11 '16 at 14:13
  • why the dislike ? – Pepernoot Nov 11 '16 at 14:23
  • @CodeJoy: A mystery of StackOverflow; don't worry too much about a single vote. – Matthieu M. Nov 11 '16 at 14:24

1 Answers1

2

Yes and No. Rust will create a reference to a reference (since you asked explicitly for it with the & operator), and then immediately "autoderef" it again to fit the target type. The optimizer will then eliminate that intermediate reference.

oli_obk
  • 28,729
  • 6
  • 82
  • 98