在模式匹配时,您可以使用 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;
}
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