What's the difference between ref and & when assigning a variable from a reference?

前端 未结 3 1553
一生所求
一生所求 2020-12-19 07:32

What is wrong with this code?

fn example() {
    let vec = vec![1, 2, 3];
    let &_y = &vec;
}


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-19 08:27

    The same symbol (&) is doing two different things when used on the right-end and left-end side of a binding. The left-hand side works like a pattern matching, so:

    let x = (y, z); // x contains a tuple with value (y, z)
    let (a, b) = x  // x is destructured into (a, b), so now
                    // a has value y and b has value z
    

    In the same way

    let x = &y; // x is a reference to y
    let &z = x; // this is like let &z= &y, so we want z to be y
                // this is equivalent to let z = *x
    

    A ref binding on the left side is saying "pattern match by reference, not by value". So these two statements are equivalent:

    let ref y = vec;
    let y = &vec;
    

    although in a let, the second one is more idiomatic.

    You can see more examples on the pointers/ref chapter on rust by example

提交回复
热议问题