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

前端 未结 2 1317
-上瘾入骨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 09:14

    Below code may give an idea for the possible solution to the problem. It's just a sample & testable code to provide a tiny example that aimed at the issue. Of course it may not cover the whole intents and purposes.

    fn main() {
        let mut score = Some(42i32);
    
        let res = if let Some(41) = score {
            println!("41 is matched");
            1i32
        } else if let Some(ref mut s) = score { //&mut score {
            //let mut s2 = s;
            //println!("s: {:#?}", s);
            test(&mut &mut *s); // This part may be like this for borrowing
            //println!("s: {:#?}", s);
            1i32
        } else {
            0i32
        };
    
        //println!("Result: {:#?}", score);
        assert_eq!(res, 1i32);
    }
    
    fn test(ref mut s: &mut &mut i32) -> i32 {
        //let mut s2 = s;
        return test2(&mut *s);
    }
    
    fn test2(n: &mut i32) -> i32 {
        *n += 1;
        //println!("Value: {}", *(*n));
        return *n;
    }
    

    Live Version: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7c3e7e1ee712a31f74b201149365035f

    Gist Link: https://gist.github.com/7c3e7e1ee712a31f74b201149365035f

提交回复
热议问题