我有一个需要变量所有权的第三方库的功能。不幸的是,这个变量在一个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
我尝试使用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
我不知道如何正确地做到这一点。