[英]move occurs because value has type `RefCell<…>`, which does not implement the `Copy` trait
UPDATE My real problem was caused by my IDE having auto-imported use std::borrow::{Borrow, BorrowMut};
更新我真正的问题是由我的 IDE 自动导入
use std::borrow::{Borrow, BorrowMut};
. . With this line, the accepted answer also doesn't compile .
有了这一行,接受的答案也不会 compile 。 The solution was removing the line.
解决方案是移除线路。
I'm getting the following error message:我收到以下错误消息:
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
and I have no idea why, or how to fix the code.而且我不知道为什么或如何修复代码。
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()
method will consume the RefCell
instance to give you the wrapped value. into_inner()
方法将使用RefCell
实例为您提供包装的值。
To achieve that, it requires you to have ownership over the instance of RefCell
.要实现这一点,它需要您拥有
RefCell
实例的所有权。 But you don't have that as it is within Rc
and unless you consume the Rc
as well to get ownership of RefCell
, you can't call into_inner()
.但是你没有它,因为它在
Rc
中,除非你也使用Rc
来获得RefCell
的所有权,否则你不能调用into_inner()
。
In your code, due to deref coersion, you get immutable ref to the inside RefCell
so you can only call methods that accept &self
.在您的代码中,由于 deref coersion,您会获得内部
RefCell
的不可变 ref,因此您只能调用接受&self
的方法。
If you want mutate the contents inside RefCell
, you can do it as follows:如果你想改变
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()
takes an immutable ref to RefCell
instance and lets you get a mutable ref to the wrapped value with which you can mutate the contents of the wrapped value. borrow_mut()
对RefCell
实例采用不可变的引用,并让您获得对包装值的可变引用,您可以使用它来改变包装值的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.