本文介绍了是否可以在模式中创建可变引用的可变值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在进行模式匹配时,您可以使用 ref mut
指定您希望获得对所包含值的可变引用:
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 = Some(42);
if let Some(ref mut s) = score {
&mut s;
}
但是,内部值是不可变的:
However, the inner value is not mutable:
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
我尝试添加另一个 mut
,但这是无效的:
I tried to add in another mut
, but that was not valid:
if let Some(mut ref mut s) = score {
&mut s;
}
error: the order of `mut` and `ref` is incorrect
--> src/main.rs:3:17
|
3 | if let Some(mut ref mut s) = score {
| ^^^^^^^ help: try switching the order: `ref mut`
error: expected identifier, found keyword `mut`
--> src/main.rs:3:25
|
3 | if let Some(mut ref mut s) = score {
| ^^^ expected identifier, found keyword
error: expected one of `)`, `,`, or `@`, found `s`
--> src/main.rs:3:29
|
3 | if let Some(mut ref mut s) = score {
| ^ expected one of `)`, `,`, or `@` here
推荐答案
不是直接的答案,而是可能的解决方法
Not a direct answer, but possible workarounds
if let Some(ref mut s) = score {
let mut s = s;
&mut s;
}
#[derive(Debug)]
struct X;
enum Foo<T> {
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);
}
}
对于 Option
专门
if let Some(ref mut s) = score.as_mut() {
s; //:&mut &mut i32
}
if let Some(mut s) = score.as_mut() {
&mut s;
}
这篇关于是否可以在模式中创建可变引用的可变值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!