Is it possible to create a mutable value of a mutable reference in a pattern?

前端 未结 2 1292
-上瘾入骨i
-上瘾入骨i 2021-01-18 08:54

When pattern-matching, you can specify that you\'d like to get a mutable reference to the contained value by using ref mut:

let mut score = Som         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 08:54

    Not a direct answer, but possible workarounds

    Create an intermediate variable

    if let Some(ref mut s) = score {
        let mut s = s;
        &mut s;
    }
    
    #[derive(Debug)]
    struct X;
    
    enum Foo {
        Bar(T),
        _Baz,
    }
    
    fn main() {
        let mut score = Foo::Bar(X);
    
        if let Foo::Bar(ref mut s) = score {
            //let x = s;
            //println!("{:?}", **x); ! not possible
            let x = &mut &mut *s; // &mut &mut X
            println!("{:?}", **x);
        }
    }
    

    For Option specifically

    if let Some(ref mut s) = score.as_mut() {
        s; //:&mut &mut i32
    }
    
    if let Some(mut s) = score.as_mut() {
        &mut s;
    }
    

提交回复
热议问题