我具有需要变量所有权的第三方库的功能。不幸的是,该变量位于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)
}
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
我尝试使用How can I swap in a new value for a field in a mutable reference to a structure?中的std::mem::replace(...)
:
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);
}
}
error[E0507]: cannot move out of an `Rc`
--> src/main.rs:11:51
|
11 | let mut foo_replaced = std::mem::replace(&mut foo.into_inner(), None);
| ^^^ move occurs because value has type `std::cell::RefCell<std::option::Option<Foo>>`, which does not implement the `Copy` trait
我不知道该怎么做。