如何在同一元素上的另一个可变迭代中迭代可变元素? [英] How to iterate over mutable elements inside another mutable iteration over the same elements?
问题描述
我有一个 Element
的数组,我想遍历它来做一些事情,然后遍历循环内的所有 Element
来做一些事情.元素之间存在关系,因此我想迭代所有其他元素以检查某些内容.由于某些原因,元素是可变引用.它有点宽泛,但我正在尝试通用(也许我不应该).
I have an array of Element
s and I want to iterate over it to do some stuff, then iterate over all Element
s inside the loop to do something. There is a relation between elements so I want to iterate to all other elements to check something. The elements are mutable references for reasons. It's a bit broad, but I'm trying to be general (maybe I should not).
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);
}
}
}
正如预期的那样,我收到了这个错误:
As expected, I got this error:
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 中的行为,但是避免此错误的推荐方法是什么?我应该先复制元素吗?忘记循环并以不同的方式迭代?了解代码设计?
I know it's a normal behavior in Rust, but what's the recommended way to avoid this error? Should I copy the elements first? Forget about loops and iterate in a different way? Learn about code design?
是否有一种 Rusty 方法可以做到这一点?
Is there a Rusty way to do this?
推荐答案
您可以使用索引迭代而不是使用迭代器进行迭代.然后,在内部循环中,您可以使用 split_at_mut
将两个可变引用获取到同一个切片中.
You can use indexed iteration instead of iterating with iterators. Then, inside the inner loop, you can use split_at_mut
to obtain two mutable references into the same slice.
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);
}
}
这篇关于如何在同一元素上的另一个可变迭代中迭代可变元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!