loops - 比较列表中的所有元素并获取匹配对的可变引用

标签 loops rust iterator borrow-checker borrowing

我的目标是根据某些标准将列表中的每个元素与列表中的每个其他元素进行比较。在伪代码中,类似于:

for i, x in list.enumerate():
    for y in list[i..]:
        if x.match(y):
            // Modify both x and y

我想获得对每个匹配对中的两个项目的可变引用。事实证明这很困难。根据this answer ,获得对列表中多个项目的可变引用的最佳方法是通过 split_at_mut 。我编写了一个包装函数,用于提取对列表的两个可变引用:

/// Gets two mutable references to elements i and j in list
fn get_pair<'a, T>(i: usize, j: usize, list: &'a mut [T]) -> (&'a mut T, &'a mut T) {
    let (a, b) = list.split_at_mut(j);

    let first = &mut a[i];
    let second = &mut b[0];

    (first, second)
}

但是,我仍然无法在嵌套 for 循环中使用此函数而不违反借用规则:

for stuff1 in list.iter() {
    // immutable borrow on list here
    for stuff2 in list[i..].iter() {
        if stuff1.compare(stuff2) {
            let (stuff1, stuff2) = get_pair(i, j, list); // mutable borrow on list
            do_something(stuff1, stuff2);
        }
    }
}

相反,我保存一对匹配的索引,然后在不同的循环中实际获取元素并用它们做一些事情。

// Find matching pairs and push their indices
let mut matches: Vec<(usize, usize)> = Vec::new();
for (i, stuff1) in list.iter().enumerate() {
    for (j, stuff2) in list[i..].iter().enumerate() {
        if stuff1.compare(stuff2) {
            matches.push((i, j));
        }
    }
}

// Get two mutable references by indices from list
for m in matches.iter() {
    let (i, j) = m;
    let (stuff1, stuff2) = get_pair(*i, *j, list);
    do_something(stuff1, stuff2);
}

这可行,但似乎有点过于复杂。是否有更简单或更简单的方法可以在不违反借用规则的情况下实现此目的?

理想情况下,我想修改原始循环中的匹配对,而不需要单独的循环来遍历索引。

我当前代码的完整示例可以在 playground 上找到。 .

最佳答案

你可以这样做,它会生成相当不错的代码:

let mut list = [1, 2, 3];
for i in 0..list.len() {
    let (a, b) = list.split_at_mut(i);
    let item_b = &mut b[0];
    for item_a in a {
        println!("{} {}", item_a, item_b);
    }
}

这里的关键是 0..len 迭代避免将 list 锁定为只读。 split_at_mut 向借用检查器证明两个引用不能指向同一元素。

关于loops - 比较列表中的所有元素并获取匹配对的可变引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53751034/

相关文章:

Javascript:当字符串连接时,新的正则表达式会破坏 for 循环迭代器

ruby - 如何在遍历数组时修改迭代器

c - 字符串字符处理 : How can I combine a post-processing loop into the primary loop?

string - Rust 的 `String` 和 `str` 有什么区别?

java - 如果给出无效响应,请重新运行 main 方法?

rust - 装箱类型时是否有最佳实践?

rust - 指示 crate 生成的文档适用于哪个版本

c++ - 如何检查 std::next(x) 是否指向 C++ 中的有效地址?

postgresql - 循环 CopyTo 查询

mysql - Power Query 中的循环计算