更新
我的真正问题是由我的IDE自动导入了use std::borrow::{Borrow, BorrowMut};
引起的。
在此行中,接受的答案为also doesn't compile。
解决方案是删除生产线。
我收到以下错误消息:
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
我不知道为什么,或如何修复代码。Playground:
#![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强制,您对RefCell
内部的引用是不可变的,因此您只能调用接受&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")]);
}
Playgroundborrow_mut()
对RefCell
实例使用不可变的引用,并让您获得对包装值的可变引用,您可以使用该引用对包装值的内容进行突变。
关于rust - 发生移动是因为值的类型为 `RefCell<…>`,它没有实现 `Copy`特质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65046411/