【问题标题】:move occurs because value has type `RefCell<...>`, which does not implement the `Copy` traitmove 发生是因为 value 的类型为 `RefCell<...>`,它没有实现 `Copy` 特征
【发布时间】:2020-11-28 04:28:17
【问题描述】:

更新 我真正的问题是由于我的 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")]);
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    into_inner() 方法将使用 RefCell 实例为您提供包装的值。

    为此,您需要拥有RefCell 实例的所有权。但是你没有它,因为它在Rc 中,除非你同时使用Rc 来获得RefCell 的所有权,否则你不能调用into_inner()


    在您的代码中,由于 deref coersion,您会获得内部 RefCell 的不可变引用,因此您只能调用接受 &amp;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")]);
    }
    

    Playground

    【讨论】:

    • 谢谢,这解决了我的问题。我已经尝试过了,但是您的代码使我确定了原因。显然我的 IDE 已经自动导入了“使用 std::borrow::{Borrow, BorrowMut};”,这也导致无法使用 .borrow_mut 进行编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2022-06-16
    • 2019-12-08
    • 2015-11-11
    • 2015-07-15
    • 2015-10-08
    • 1970-01-01
    相关资源
    最近更新 更多