Move the error to for-loop if you do not reinstall the modified fragment

I am trying to pass a modified fragment of a function and use it in several loops inside it.

function1causes an error. Switching to function2or function3leads to the disappearance of errors, but I do not understand the differences between function1and function2. vand &mut *vseem like me.

Why function1doesn't it work while others do?

fn main() {
    let mut v = Vec::new();

    function1(&mut v);
    function2(&mut v);
    function3(&mut v);
}

// Move Error 
fn function1(v: &mut [i32]) {
    for l in v {}
    for l in v {} // <-- Error Here !!!
}

// Works Fine
fn function2(v: &mut [i32]) {
    for l in &mut *v {}
    for l in &mut *v {}
}

// Works Fine
fn function3(v: &mut [i32]) {
    for l in v.iter_mut() {}
    for l in v.iter_mut() {}
}

Error:

error[E0382]: use of moved value: `v`
  --> src/main.rs:12:14
   |
11 |     for l in v {}
   |              - value moved here
12 |     for l in v {} // <-- Error Here !!!
   |              ^ value used here after move
   |
   = note: move occurs because `v` has type `&mut [i32]`, which does not implement the `Copy` trait
+4
source share
1 answer

&mut *v performs the so-called "reborrow".

This means that instead of iterating over the original link, you are repeating the new link.

Think of it this way:


, , , for.

, , .


, , for. .

, , . , , , .

+3

Source: https://habr.com/ru/post/1686999/


All Articles