rust - 发生移动是因为值的类型为 `RefCell<…>`,它没有实现 `Copy`特质

标签 rust

更新
我的真正问题是由我的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")]);
}
Playground
borrow_mut() RefCell实例使用不可变的引用,并让您获得对包装值的可变引用,您可以使用该引用对包装值的内容进行突变。

关于rust - 发生移动是因为值的类型为 `RefCell<…>`,它没有实现 `Copy`特质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65046411/

相关文章:

c++ - 不使用指针的递归数据结构

mongodb - 使用 mongodb-1.2.2 和 Rocket-0.5.0-rc.1 时如何解决异步不兼容问题?

rust - 在 Arc 和 Mutex 后面调用 Trait 对象的方法

c - 是否可以使用C从Rust内置的静态库中调用函数?

c++11 - Rust 中的 C+11 类类型衰减

rust - `token` 在 rust 中传递到 HeaderValue 时存活时间不够长

vector - 通过迭代而不是使用 .push() 逐一填充结构体元素的向量

optimization - 为什么这段代码生成的汇编比等效的 C++/Clang 多得多?

rust - reqwest::Error { kind: Decode, source: Error ("expected value", line: 1, column: 1) }'

rust - 如何设置 actix websocket actorless 的消息大小限制?