How to solve this "used of moved value" issue

I am new to Rust. Currently I'm confused about this kind of problem. My code may look like this:

pub fn test(mut a: Vec<u8>) -> (Vec<u8>, i32) {
    let mut b  = Vec::new();
    let mut c = 0;
    loop {
        if a.len() == 0 { break; }
        let d = a.pop();
        c = c+d;
    (b, c)

fn borrow_test() {
    let mut a = vec![1,2,3,4,5];
    let mut i = 0;
    let c = 0;
    loop {
        let (a, c) = test(a);
        if i >=5 {break;}

I was thinking every time I call test(a), it will return a new one and then go through this loop.
But seem like it is wrong.
Could someone tell me how to solve this kind of problem?

Thanks in advance

Your code gives this error:

error[E0277]: cannot add `Option<u8>` to `{integer}`
 --> src/
7 |         c = c+d;
  |              ^ no implementation for `{integer} + Option<u8>`
  = help: the trait `Add<Option<u8>>` is not implemented for `{integer}`

This is because the pop method returns an optional value in case the vector is empty. To get it to compile you can do this:

let d = a.pop().unwrap();
c = c + (d as i32);

Next you get this error:

error[E0382]: use of moved value: `a`
  --> src/
15 |     let mut a = vec![1,2,3,4,5];
   |         ----- move occurs because `a` has type `Vec<u8>`, which does not implement the `Copy` trait
19 |         let (a, c) = test(a);
   |                           ^ value moved here, in previous iteration of loop

This is because you can only give away ownership of a value once. To fix it, you can clone the vector.

let (a, c) = test(a.clone());

Note that the let (a, c) part does not overwrite the a variable - rather, it declares a new variable also called a, shadowing the old one. To modify the existing variable, you can do this:

let (a_new, c) = test(a.clone());
a = a_new;

Similarly for c.

Added: If you overwrite a with a new value before the next iteration of the loop, the compiler will actually allow you to give away ownership because you have obtained a new value before the next iteration of the loop.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.