简体   繁体   English

rust中嵌套for循环,修改vector中的元素

[英]Nested for loop in rust, modifying elements in a vector

I am trying to create a nested loop in rust, that goes through a vector.我正在尝试在 rust 中创建一个嵌套循环,它通过一个向量。 Essentially, it looks like this:本质上,它看起来像这样:

fn main() {
    let v = vec![1, 2, 3];
    
    for i in &mut v {
        for j in &mut v {
            if i == j {
                *i = *j + 1;
            }
        }
    }
    
    println!("{:?}", v);
}

However, this will not work;但是,这是行不通的; Rust cannot borrow as mutable more than once. Rust 不能多次作为可变借用。

In my case, this the elements in the vector are structs that have non copy-able elements inside of them.在我的例子中,向量中的元素是内部具有不可复制元素的结构。 How could rust go about doing something like this? rust go 怎么可能做这样的事情?

You'll have to use indexing in this case as a work around, which will create more localized borrows and satisfy the borrow checker:在这种情况下,您必须使用索引作为解决方法,这将创建更多本地化借用并满足借用检查器的要求:

fn main() {
    let mut v = vec![1, 2, 3];

    for i in 0..v.len() {
        for j in 0..v.len() {
            if v[i] == v[j] {
                v[i] = v[j] + 1;
            }
        }
    }

    println!("{:?}", v);
}

Output: Output:

[4, 4, 4]

Playground 操场

Here, only v[i] is borrowed mutably for a moment while it is assigned the value of v[j] + 1 .在这里,只有v[i]被可变地借用了一会儿,同时它被赋予了v[j] + 1的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM