小编Vec*_*ous的帖子

为什么unwrap_or()继续在范围内借用?

试图编译:

fn main() {
    let mut vec = vec![1, 2, 3];
    let four: &mut u32 = borrow_or_add(&mut vec, 4);
}

fn borrow_or_add(vec: &mut Vec<u32>, val: u32) -> &mut u32 {
    vec.iter_mut().find(|v| **v == val).unwrap_or({
        vec.push(val);

        vec.last_mut().unwrap()
    })
}
Run Code Online (Sandbox Code Playgroud)

操场

...给出以下结果:

q.rs:8:9: 8:12 error: cannot borrow `*vec` as mutable more than once at a time
q.rs:8         vec.push(val);
               ^~~
q.rs:7:5: 7:8 note: previous borrow of `*vec` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*vec` until the borrow …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
362
查看次数

标签 统计

rust ×1