我试图使创建和管理子对象的父对象受到反对。它从工厂函数返回&RefCell,然后可以用来借用子对象。我将代码浓缩到下面的示例:
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();
}但是,当我试图引用子引用时,它会导致以下编译错误:
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而不会导致一个错误?
发布于 2022-02-27 16:24:12
在有一个RefCell的地方,一个Rc可能就在附近,但是现在我让它在没有编译的情况下编译(同时也删除了用于额外极简主义的Box )。一旦您试图让这段代码做一些有用的事情,可能就不再有效了。
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();
}https://stackoverflow.com/questions/71286214
复制相似问题