是否有可能在模式中创建可变引用的可变值?

时间:2018-04-07 18:28:53

标签: rust pattern-matching

当模式匹配时,您可以使用opacity: 0.5指定您希望获得对包含值的可变引用:

ref mut

但是,内在值不可变:

let mut score = Some(42);
if let Some(ref mut s) = score {
    &mut s;
}

我可以通过使用新的可变绑定来隐藏变量来解决这个问题:

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

有没有办法在模式中同时执行此操作?我尝试添加另一个if let Some(ref mut s) = score { let mut s = s; &mut s; } ,但这无效:

mut
if let Some(mut ref mut s) = score {
    &mut s;
}

2 个答案:

答案 0 :(得分:2)

不是直接答案,但可能的解决方法

创建一个中间变量

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;
}

答案 1 :(得分:0)

下面的代码可能为解决该问题提供了一个思路。这只是一个示例和可测试的代码,提供了一个针对该问题的小例子。当然,它可能无法涵盖全部意图和目的。

SELECT FORMAT(HIREDATE, 'dd-MMM-yy')
  FROM emp

实时版本:do this

要害链接:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7c3e7e1ee712a31f74b201149365035f