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

前端 未结 3 1538
一生所求
一生所求 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:11

    First of all, you do not need the & in your working example. If you use it, you end up with a &&Vec<_>, which you don't really need.

    let vec = vec![1, 2, 3];
    let ref y = vec;
    

    The problem with your first code is that you are doing two things at once. Lets split it up into two:

    The first part creates a reference to vec

    let y1 = &vec;
    

    The second part (the & before the variable binding), destructures.

    let &y2 = y1;
    

    This means you are trying to move out of the reference, which only works if the type is Copy, because then any attempt to move will copy the object instead.

提交回复
热议问题