我有一个Element
s数组,我想遍历它做一些事情,然后遍历循环Element
内的所有s做某事。元素之间存在关系,因此我想遍历所有其他元素以进行检查。出于某些原因,这些元素是可变的引用。有点宽泛,但是我想变得笼统(也许我不应该)。
struct Element;
impl Element {
fn do_something(&self, _e: &Element) {}
}
fn main() {
let mut elements = [Element, Element, Element, Element];
for e in &mut elements {
// Do stuff...
for f in &mut elements {
e.do_something(f);
}
}
}
不出所料,我收到此错误:
error[E0499]: cannot borrow `elements` as mutable more than once at a time
--> src/main.rs:13:18
|
10 | for e in &mut elements {
| -------------
| |
| first mutable borrow occurs here
| first borrow later used here
...
13 | for f in &mut elements {
| ^^^^^^^^^^^^^ second mutable borrow occurs here
我知道这是Rust中的正常行为,但是如何避免这种错误的推荐方法是什么?我应该先复制元素吗?忘记循环并以其他方式进行迭代?了解代码设计?
有生锈的方法吗?
您可以使用索引迭代,而不是使用迭代器进行迭代。然后,在内部循环内,您可以使用split_at_mut
来获取同一切片中的两个可变引用。
for i in 0..elements.len() {
for j in 0..elements.len() {
let (e, f) = if i < j {
// `i` is in the left half
let (left, right) = elements.split_at_mut(j);
(&mut left[i], &mut right[0])
} else if i == j {
// cannot obtain two mutable references to the
// same element
continue;
} else {
// `i` is in the right half
let (left, right) = elements.split_at_mut(i);
(&mut right[0], &mut left[j])
};
e.do_something(f);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句