rust icon indicating copy to clipboard operation
rust copied to clipboard

'error: illegal borrow: borrowed value does not live long enough' on chained methods that return &'self pointers

Open Kimundi opened this issue 13 years ago • 2 comments

trait Foo {
    fn a(&self) -> &'self str;
    fn b(&self) -> &'self str;
}

impl Foo for &'self str {
    fn a(&self) -> &'self str {
        *self
    }
    fn b(&self) -> &'self str {
        *self
    }
}

fn main () {
    let c = "defg";
    c.a();
    c.b();
    c.a().b(); // error: illegal borrow: borrowed value does not live long enough
}

Kimundi avatar Mar 21 '13 18:03 Kimundi

Since I got an error message "Illegal lifetime 'self: the self lifetime must be declared" on several lines, I added declare like below and it doesn't occur any error now.

trait Foo<'self> {
    fn a(&self) -> &'self str;
    fn b(&self) -> &'self str;
}

impl<'self> Foo<'self> for &'self str {
    fn a(&self) -> &'self str {
        *self
    }
    fn b(&self) -> &'self str {
        *self
    }
}

fn main () {
    let c = "defg";
    c.a();
    c.b();
    c.a().b();
}

june0cho avatar May 16 '13 05:05 june0cho

works on latest. seems no more issue.

yichoi avatar May 16 '13 05:05 yichoi