如何使用 Rc<RefCell<Option<_>>> 的内部值?

Nat*_*tjo 6 rust refcell

我有一个第三方库的函数,需要变量的所有权。不幸的是这个变量在Rc<RefCell<Option<Foo>>>.

我的代码看起来像这样简化:

use std::cell::RefCell;
use std::rc::Rc;

pub struct Foo {
    val: i32,
}

fn main() {
    let foo: Rc<RefCell<Option<Foo>>> = Rc::new(RefCell::new(Some(Foo { val: 1 })));

    if let Some(f) = foo.into_inner() {
        consume_foo(f);
    }
}

fn consume_foo(f: Foo) {
    println!("Foo {} consumed", f.val)
}
Run Code Online (Sandbox Code Playgroud)
use std::cell::RefCell;
use std::rc::Rc;

pub struct Foo {
    val: i32,
}

fn main() {
    let foo: Rc<RefCell<Option<Foo>>> = Rc::new(RefCell::new(Some(Foo { val: 1 })));

    if let Some(f) = foo.into_inner() {
        consume_foo(f);
    }
}

fn consume_foo(f: Foo) {
    println!("Foo {} consumed", f.val)
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用std::mem::replace(...)来自How can I swap in a new value for a field in a mutable引用结构?:

fn main() {
    let mut foo: Rc<RefCell<Option<Foo>>> = Rc::new(RefCell::new(Some(Foo { val: 1 })));

    let mut foo_replaced = std::mem::replace(&mut foo.into_inner(), None);
    if let Some(f) = foo_replaced.take() {
        consume_foo(f);
    }
}
Run Code Online (Sandbox Code Playgroud)
error[E0507]: cannot move out of an `Rc`
  --> src/main.rs:11:22
   |
11 |     if let Some(f) = foo.into_inner() {
   |                      ^^^ move occurs because value has type `std::cell::RefCell<std::option::Option<Foo>>`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)

我不知道如何正确地做到这一点。