首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >借用A &RefCell会导致多个可变借款

借用A &RefCell会导致多个可变借款
EN

Stack Overflow用户
提问于 2022-02-27 15:51:41
回答 1查看 249关注 0票数 1

我试图使创建和管理子对象的父对象受到反对。它从工厂函数返回&RefCell,然后可以用来借用子对象。我将代码浓缩到下面的示例:

代码语言:javascript
复制
use std::{collections::HashMap, cell::RefCell, error::Error};

struct Child(i32);

impl Child {
    pub fn new(id: i32) -> Child {
        Child(id)
    }
}

struct Parent {
    children: HashMap<i32, Box<RefCell<Child>>>
}

impl Parent {
    pub fn new() -> Parent {
        Parent {
            children: HashMap::new()
        }
    }

    pub fn create_child(&mut self, id: i32) -> &RefCell<Child> {
        let child = Child::new(id);
        let cell = Box::new(RefCell::new(child));
        self.children.insert(id, cell);
        return self.children.get(&id).unwrap();
    }

    pub fn beep(&mut self) {

    }
}

fn main() {
    let mut parent = Parent::new();
    let child1 = parent.create_child(1);
    let child2 = parent.create_child(2);
    child1.borrow();
}

但是,当我试图引用子引用时,它会导致以下编译错误:

代码语言:javascript
复制
error[E0499]: cannot borrow `parent` as mutable more than once at a time
  --> foo\src\main.rs:37:18
   |
36 |     let child1 = parent.create_child(1);
   |                  ---------------------- first mutable borrow occurs here
37 |     let child2 = parent.create_child(2);
   |                  ^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
38 |     child1.borrow();
   |     --------------- first borrow later used here

是否有一种方法可以让我返回一个&RefCell而不会导致一个错误?

EN

回答 1

Stack Overflow用户

发布于 2022-02-27 16:24:12

在有一个RefCell的地方,一个Rc可能就在附近,但是现在我让它在没有编译的情况下编译(同时也删除了用于额外极简主义的Box )。一旦您试图让这段代码做一些有用的事情,可能就不再有效了。

代码语言:javascript
复制
use std::{collections::HashMap, cell::RefCell};

struct Child(i32);

impl Child {
    pub fn new(id: i32) -> Child {
        Child(id)
    }
}

struct Parent {
    children: HashMap<i32, RefCell<Child>>
}

impl Parent {
    pub fn new() -> Parent {
        Parent {
            children: HashMap::new()
        }
    }

    pub fn create_child(&mut self, id: i32) {
        let child = Child::new(id);
        let cell = RefCell::new(child);
        self.children.insert(id, cell);
    }

    pub fn get_child(&self, id: i32) -> &RefCell<Child> {
        self.children.get(&id).unwrap()
    }
}

fn main() {
    let mut parent = Parent::new();
    {
        parent.create_child(1);
        parent.create_child(2);
    }
    let child1 = parent.get_child(1);
    let child2 = parent.get_child(2);
    child1.borrow();
    child2.borrow();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71286214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档