Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can't figure out how to get the following to work. I think I need the closure to borrow by &mut Vec, but I don't know how to express that. This is distilled from a larger function, but shows the same error.

fn main() {
    let mut v = vec![0; 10];

    let next = |i| (i + 1) % v.len();

    v[next(1usize)] = 1;

    v.push(13);

    v[next(2usize)] = 1;    
}

Error:

error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> a.rs:9:5
  |
5 |     let next = |i| {
  |                --- immutable borrow occurs here
6 |         (i + 1) % v.len()
  |                   - first borrow occurs due to use of `v` in closure
...
9 |     v[next(1usize)] = 1;
  |     ^ ---- immutable borrow later used here
  |     |
  |     mutable borrow occurs here

error: aborting due to previous error
question from:https://stackoverflow.com/questions/65646778/mutable-vs-immutable-borrows-in-closure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
451 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you really want to do it with a closure, you will have to pass the vector by parameter:

let next = |v: &Vec<_>, i| (i + 1) % v.len();

This makes the closure borrow per-call, rather than capture for the scope. You still need to separate the borrows, though:

let j = next(&v, 1usize);
v[j] = 1;

To make your life easier, you can put everything inside the closure instead:

let next = |v: &mut Vec<_>, i, x| {
    let j = (i + 1) % v.len();
    v[j] = x;
};

Which allows you to simply do:

next(&mut v, 1usize, 1);
next(&mut v, 2usize, 2);
// etc.

This pattern is useful for cases where you are writing a closure just for avoiding local code repetition (which I suspect is why you are asking given the comments).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...