She*_*ter 7 pattern-matching rust
在进行模式匹配时,您可以使用以下命令指定要获取对所包含值的可变引用ref mut:
let mut score = Some(42);
if let Some(ref mut s) = score {
&mut s;
}
Run Code Online (Sandbox Code Playgroud)
但是,内部值是不可变的:
let mut score = Some(42);
if let Some(ref mut s) = score {
&mut s;
}
Run Code Online (Sandbox Code Playgroud)
我试图添加另一个mut,但这是无效的:
if let Some(mut ref mut s) = score {
&mut s;
}
Run Code Online (Sandbox Code Playgroud)
error[E0596]: cannot borrow immutable local variable `s` as mutable
--> src/main.rs:4:14
|
4 | &mut s;
| ^
| |
| cannot reborrow mutably
| try removing `&mut` here
Run Code Online (Sandbox Code Playgroud)
Erd*_*sci -1
下面的代码可能会给出问题的可能解决方案的想法。这只是一个示例和可测试的代码,提供了一个针对该问题的小示例。当然,它可能无法涵盖全部意图和目的。
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;
}
Run Code Online (Sandbox Code Playgroud)
要点链接:https://gist.github.com/7c3e7e1ee712a31f74b201149365035f