Borrow checker help

Hi All,

I have recently started learning Rust and got stuck into the borrow checker conundrum, below is a miniaturized version of my program which is resulting in "i does not live long enough" error, would appreciate any help getting around this. I cannot change enum T as it is defined in an external crate I am using. I tried playing around with RefCell, Cell etc but not sure thats the most optimum solution.

#[derive(Debug)]
enum T<'a> {
    V1(&'a mut i32)
}

fn main() {
    let mut x : Vec<Option<i32>> = vec![Some(24), Some(55), Some(77)];
    let mut res : Vec<T> = Vec::new();
    for v in x{
        match v {
            Some(mut i) => res.push(T::V1(&mut i)),
            None => println!("Nothing")
        }
    }
    println!("res={:?}", res);
}

You do code blocks like this:

```
// your code here
```

Fixed, thanks

1 Like

Basically the issue is that in this for loop:

for v in x {

you are taking ownership of the array x, thus destroying it and taking the values out. You then do this

Some(mut i) => res.push(T::V1(&mut i)),

So here you're putting a &mut i32 into the res vector. The problem is that you destroyed the vector x, so the variable i doesn't exist in the next iteration, nor after the loop. Instead, you want to mutably borrow the vector x, which allows you to put borrows of the vector x into res, like this:

fn main() {
    let mut x: Vec<Option<i32>> = vec![Some(24), Some(55), Some(77)];
    let mut res: Vec<_> = Vec::new();
    for v in &mut x {
        match v {
            Some(i) => res.push(T::V1(i)),
            None => println!("Nothing")
        }
    }
    println!("res = {:?}", res);
}

playground

This works because iterating over a &mut Vec<_> gives you mutable references to the items in the vector without destroying the vector (and we don't have &mut i anymore because i is already a &mut i32).

That works, I overlooked the fact that iterating implicitly moved the ownership, could have also used x.iter_mut()

Thanks for the explanation.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.