我有一个 struct Region
,它包含[Option<Rc<RefCell<Region>>>; 2]
作为它的subregions
和Option<Weak<RefCell<Region>>>
作为它的container
.我正在编写一个方法,在self
和self.container
之间插入一个新的Region
,这需要我将Rc克隆到self
,以包含在新创建的Region
中作为subregions
中的一个.当self.container
是Some
时,这是可能的,因为我可以走到容器,然后克隆它与self
匹配的subregion
,但是当self
有None
作为容器时,我不知道如何从传递到方法的&mut self
中获得self
的Rc
的克隆.
这里有一些代码,使它更清晰.
struct Region {
subregions: [Option<Rc<RefCell<Region>>>; 2],
container: Option<Weak<RefCell<Region>>>,
}
impl Region {
fn clone_from_container(&self) -> Option<Rc<RefCell<Region>>> {
Some(Rc::clone(&self.container
.as_ref()?
.upgrade()
.unwrap()
.borrow()
.subregions[self.from()]
.as_ref()
.unwrap()))
}
pub fn insert_above(&mut self) -> Rc<RefCell<Region>> {
let new = Rc::new(RefCell::new(Region {
subregion: [self.clone_from_container(),None],
container: self.container.clone(),
}));
self.replace(new.clone());
self.container = Some(Rc::downgrade(&new.clone()));
new
}
}
在我的实际代码中还有几个更多的函数,但这些只是长方法链的别名,用于打开Rc
和RefCell
的包装箱,使我能够实际获取数据.我尽量只讲重要的细节.
我排除的方法,Region::replace
和Region::from
非常简单,它们的实现并不重要.replace
走到container
,用新的区域替换对self
的引用(与clone_from_container
非常相似,但改变了Region
),from
简单地在其container
的subregions
(0或1)内找到Region
的索引.
当设置new
中的subregion
时,我希望能够说self.clone_from_container().or(Rc::clone(self))
这样的东西,但显然这是不可能的,因为self
被传递为类型.
我想这可能是一个静态工厂函数,而不是一个实例方法,所以我们可以用类型Rc<RefCell<Region>>
传递self
,但我也认为可能使用Rc::new_cyclic
;然而,这个函数有点混乱,我不太确定如何使用它.