更新
我真正的问题是由我的IDE自动导入引起的use std::borrow::{Borrow, BorrowMut};
。通过这一行,可接受的答案也不会编译。解决方案是删除生产线。
我收到以下错误消息:
15 | instance_context.into_inner().instances = Some(vec![String::from("abc")]);
| ^^^^^^^^^^^^^^^^ move occurs because value has type `RefCell<InstanceContext>`, which does not implement the `Copy` trait
我不知道为什么,或如何修复代码。
游乐场:
#![allow(dead_code)]
#![allow(unused_variables)]
use std::rc::Rc;
use std::cell::RefCell;
struct InstanceContext {
id: i32,
instances: Option<Vec<String>>,
}
fn main() {
let instance_context = Rc::new(RefCell::new(InstanceContext { id: 5, instances: None }));
// clojures are created that use instance_context, which does not yet have 'instances' set
instance_context.into_inner().instances = Some(vec![String::from("abc")]);
}
into_inner()
方法将使用该RefCell
实例来为你提供包装后的值。
为此,你需要拥有实例的所有权RefCell
。但是你并没有它的存在Rc
,除非你花费了大量的时间Rc
来获得所有权,否则你RefCell
不能打电话into_inner()
。
在代码中,由于deref强制,你将获得对内部不可变的ref,RefCell
因此你只能调用accept的方法&self
。
如果你要更改其中的内容RefCell
,可以按照以下步骤进行操作:
#![allow(dead_code)]
#![allow(unused_variables)]
use std::rc::Rc;
use std::cell::RefCell;
struct InstanceContext {
id: i32,
instances: Option<Vec<String>>,
}
fn main() {
let instance_context = Rc::new(RefCell::new(InstanceContext { id: 5, instances: None }));
instance_context.borrow_mut().instances = Some(vec![String::from("abc")]);
}
borrow_mut()
将不可变的ref引用到RefCell
实例,并让你获得对包装后的值的可变引用,你可以使用该变量对包装后的值的内容进行突变。
谢谢,这解决了我的问题。我已经尝试过了,但是您的代码使我确定了原因。显然我的IDE已自动导入了“ use std :: borrow :: {Borrow,BorrowMut};”,这也导致无法使用.borrow_mut进行编译。