1

In this example code, adding a lifetime parameter 'a makes the borrow checker say cannot borrow `p` as mutable more than once at a time, but without the lifetime it compiles and runs fine. Why is this?

runnable version: https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=eef27bc134d581b35a4eaa5e6383d8d6

#[derive(Debug)]
struct Point<'a> {
    x: &'a str,
    y: i32,
}

impl<'a> Point<'a> {
    fn up(&'a mut self) { // <-- remove "'a " and it will compile and run
        self.y += 1;
    }
}

fn main() {
    let mut p = Point { x: "empty", y: 0 };
    p.up();
    p.up(); // <-- borrow checker complains here
    dbg!(p);
}

Does the borrow checker do something special with lifetimes that makes this disallowed?

Matt Woelk
  • 1,940
  • 1
  • 20
  • 24
  • After looking at the linked post, it seems the answer is that putting lifetime bounds on self in that location adds an unnecessary limit. – Matt Woelk Nov 29 '21 at 01:29

0 Answers0