我正在尝试使用Rust创建一个不相交集数据结构。相关代码如下:
pub struct Set<'a, T: 'a> {
rank: u32,
value: T,
parent: Option<&'a mut Set<'a, T>>,
}
impl<'a, T> Set<'a, T> {
pub fn find(&'a mut self) -> &'a mut Set<'a, T> {
match self.parent {
None => self,
Some(mut p) => {
self.parent = Some(p.find());
self.parent.unwrap()
}
}
}
}
我得到的错误是:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:9:15
|
9 | match self.parent {
| ^^^^ cannot move out of borrowed content
10 | None => self,
11 | Some(mut p) => {
| ----- hint: to prevent move, use `ref p` or `ref mut p`
error[E0507]: cannot move out of borrowed content
--> src/main.rs:13:17
|
13 | self.parent.unwrap()
| ^^^^ cannot move out of borrowed content
我不确定我完全理解了借用检查器,但是我正在使用引用来避免对结构体本身进行所有权控制,以便它们可以被指向和重新分配,类似于其他语言中的操作。
如果我从结构体的引用中删除 mut
,就可以避免这些错误,但是因为它们是不可变的,所以我无法更改每个集合的父级。
我已经阅读了类似的问题,例如:
- Rust:"cannot move out of `self` because it is borrowed" error
- Can't borrow File from &mut self (error msg: cannot move out of borrowed content)
这些并没有帮助我解决这个问题。我还尝试过重构函数 find
以及结构体本身,使用 Rc<RefCell<Set>>
和 Box<Set>
,但最终总是出现相同的错误。
unwrap
消耗Option
的事实有关。 - Shepmasteras_mut()
会使我返回一个对结构体的可变引用的可变引用,这似乎也行不通。即使尝试将此函数分解为每个步骤来完成也似乎没有解决问题。 - mcdonalda1993