#Help Understanding Lifetimes

24 messages · Page 1 of 1 (latest)

karmic prism
#
struct Foo<'a> {
    s: &'a str,
}

impl<'a> Foo<'a> {
    fn update(&'a mut self) {
        self.s = "asdf";
    }
}

fn main() {
    let mut foo = Foo {
        s: "blah",
    };
    
    foo.update();
    foo.update(); //error: cannot borrow foo as mutable more than once
}

I'm confused why adding the lifetime in the update function makes it so you can't call update twice due to foo already being mutably borrowed...After you call foo.update aren't there no mutable references to foo that exist? it seems like it should be fine to call update again

tropic iron
#

?play ```rust
struct Foo<'a> {
s: &'a str,
}

impl<'a> Foo<'a> {
fn update(&mut self) {
self.s = "asdf";
}
}

fn main() {
let mut foo = Foo {
s: "blah",
};

foo.update();
foo.update(); //error: cannot borrow foo as mutable more than once

}

frozen boltBOT
tropic iron
karmic prism
#

I guess I'm confused still by the compiler error when calling foo.update the second time...How could foo be mutably borrowed at that time? it would seem to me like no mutable references exist

tropic iron
karmic prism
#

update then makes a static lifetime mutable borrow?

tropic iron
#

Basically you said while "blah" exists the first borrow also does

#

(I'm glossing over variance)

tropic iron
karmic prism
#

oh this is making a lot of sense now, thank you

tropic iron
fleet lake
#

Is it like that

fleet lake
#

Which means that it doesn't drops at the end of function call .??

#
  fn update(&'a mut self){

  //  -> &'a mut self doesn't drops here
   } 

wintry wagon
#

you have the &'a mut Type<'a> pattern

#

which is not useful

fleet lake
fleet lake
wintry wagon