Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Drop borrow in each loop iteration

This is a reproducible simplification of my problem:

struct Val<'a>(&'a str);

impl Val<'_> {
    fn get(&self) -> Option<&str> {
        Some(self.0)
    }
}

// Not used here, but this borrow needs to be mutable
fn test<'a>(param: &'a mut Val<'a>) -> Option<&'a str> {
    param.get()
}

fn main() {
    let s = String::from("hello");
    let mut v = Val(&s);
    
    while let Some(x) = test(&mut v) {
        println!("{x}");
    }
}

playground link

I get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   |
17 |     while let Some(x) = test(&mut v) {
   |                              ^^^^^^
   |                              |
   |                              `v` was mutably borrowed here in the previous iteration of the loop
   |                              first borrow used here, in later iteration of loop

For more information about this error, try `rustc --explain E0499`.

First I tried to change the lifetime of the borrow, to indicate that it does not live as long as the original data, like this:

fn test<'a, 'b>(param: &'b mut Val<'a>) -> Option<&'a str> {
    param.get()
}

But then I get:

   |
9  | fn test<'a, 'b>(param: &'b mut Val<'a>) -> Option<&'a str> {
   |         --  -- lifetime `'b` defined here
   |         |
   |         lifetime `'a` defined here
10 |     param.get()
   |     ^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b`
   |
   = help: consider adding the following bound: `'b: 'a`

Adding the suggested bound brings me back to the previous error.

I checked this related question, which suggests this is a limitation of the borrow checker, so I tried changing my code to:

fn main() {
    let s = String::from("hello");
    let mut v = Val(&s);
    
    loop {
        let x = test(&mut v);
        if let Some(y) = x {
            println!("{y}");
        }
    }
}

playground link

But I get the same first error. In my use case test behaves more or less like a next from iterator, so I can’t call it two times in the same iteration.

Is there any way to:

  • return data with lifetime 'a instead of 'b in fn test?
  • or, with the single 'a lifetime, make the borrow be dropped at the end of the iteration?

>Solution :

The inherent function Val::get() has the wrong lifetime in the return value. The function returns the inner value of Val, so the return value should have the lifetime of that inner value. Due to lifetime elision, the signature of your implementation of get() is equivalent to

fn get<'b>(&'b self) -> Option<&'b str>;

In other words, self will always be borrowed for the entire lifetime of the returned value, which is unnecessary. The lifetime of the borrow of self is completely independent of the lifetime of the returned string.

You also need to decouple the two lifetimes in test(), as you already tried. Here’s the full working code:

struct Val<'a>(&'a str);

impl<'a> Val<'a> {
    fn get(&self) -> Option<&'a str> {
        Some(self.0)
    }
}

fn test<'a, 'b>(param: &'b mut Val<'a>) -> Option<&'a str> {
    param.get()
}

fn main() {
    let s = String::from("hello");
    let mut v = Val(&s);

    while let Some(x) = test(&mut v) {
        println!("{x}");
    }
}

(I added 'b for clarity in test(). You could also simply omit it and use &mut Val<'a> as the type of param, again due to lifetime elision.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading