【发布时间】:2015-03-27 11:25:16
【问题描述】:
我试图在 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这一事实有关。 -
@Shepmaster 我试过这样做,但后来我收到一个错误,告诉我我不能分配给 self.parent 因为它已经被借了。并且在第二个错误上使用
as_mut()使得我返回一个可变引用到一个似乎也不起作用的结构的可变引用。甚至试图将这个功能展开以逐步执行每个部分似乎都无法解决问题。 -
您可能还对Hand-over-hand locking with Rust 感兴趣,其中有人也在尝试实施 union-find / disjoint-set。
标签: rust mutable ownership borrow-checker