Warm tip: This article is reproduced from serverfault.com, please click

rust-发生移动是因为值的类型为RefCell,但未实现Copy特性

(rust - move occurs because value has type `RefCell`, which does not implement the `Copy` trait)

发布于 2020-11-28 04:28:17

更新 我真正的问题是由我的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")]);
}
Questioner
xoa991x
Viewed
0
Mihir 2020-11-28 13:25:47

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实例,并让你获得对包装后的值的可变引用,你可以使用该变量对包装后的值的内容进行突变。