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

Why method with lifetime specified cannot be called twice?

struct A<'a> {
    v: &'a str,
}

impl<'a> A<'a> {
    pub fn test(&'a mut self) {
        self.trivial();

        // Compiling error info:
        //       cannot borrow `*self` as mutable more than once at a time
        // first mutable borrow occurs here (last called self.trivial())
        self.trivial(); // Compiling error line.
    }

    // Trivial empty function.
    fn trivial(&'a mut self) {}
}

The compiling errors happen at the second called self.trivial() and compiler hints that it’s the first calling self.trivial mutably borrow *self. And if the trivial function is defined by removing the lifetime ‘a then everything is fine.

// ok then if no 'a specified.
fn trivial(&mut self) {}

My question is why does the lifetime 'a influence the borrowing? I think function trivial has the parameter with type &mut which just accepts the argument and not borrow at all, how does the first calling borrow?

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

>Solution :

The name of the lifetime matters. When you give it 'a as an explicit lifetime, you’re saying the &mut self ref given to trivial must remain accessible for the lifetime of the struct itself. Which means it doesn’t get "released" after the first call to trivial. If you change that to trivial having its own lifetime:

fn trivial<'b>(&'b mut self) {}

Now it’ll work fine because the borrow only lasts as long as the function call. This is the same thing that’s happening implicitly if you remove the lifetime annotation entirely.

Note that passing a &mut self (or any reference) into a function is a borrow — "accepts an argument and not borrow at all" doesn’t really make sense when that argument is a ref.

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