Rust by example: The ref pattern

后端 未结 2 572
终归单人心
终归单人心 2021-01-12 21:10

I have problems understanding the ref pattern in Rust. I am referring to https://rustbyexample.com/scope/borrow/ref.html

Here is the code I don\'t under

2条回答
  •  佛祖请我去吃肉
    2021-01-12 21:46

    A reference created with ref is exactly the same as reference taken with &.

    The difference is where they're allowed in the syntax. ref on the left side of an assignment is like adding & on the right side.

    These expressions are equivalent:

    let ref x1 = y;
    let x2 = &y;
    

    This redundancy exists because in pattern matching & is used to require that a reference exists already, rather than to make a new one:

    let foo = 1;
    match foo {
       ref x => {
           /* x == &1 */ 
           match x {
               &y => /* y == 1 */
           }
       },  
    }
    

    (discussion)

提交回复
热议问题