小编Ric*_*len的帖子

在循环内借用向量

我试图更新向量的每个元素,然后在每次迭代期间借用整个向量,例如:

#![allow(unused)]

#[derive(Debug)]
pub struct Foo {
    value: i32,
}

fn main() {
    let mut foos: Vec<Foo> = vec![Foo { value: 1 }, Foo { value: 2 }, Foo { value: 3 }];

    for foo in &mut foos {
        update_single(foo);

        //save_all(&foos); <-- this doesn't compile - there's already a mutable borrow
    }
}

fn update_single(foo: &mut Foo) {
    println!("update_single");
    foo.value *= foo.value;
}

fn save_all(foos: &Vec<Foo>) {
    println!("save_all:");
    for foo in foos {
        println!("\t{:?}", foo);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我将更新后的向量保存为 blob,例如 via …

iterator vector rust borrow-checker

3
推荐指数
1
解决办法
1543
查看次数

标签 统计

borrow-checker ×1

iterator ×1

rust ×1

vector ×1