Why the borrow checker is ok with `self:&'a` for a struct Foo<'a>

PressRex profile image
by PressRex
Why the borrow checker is ok with `self:&'a` for a struct Foo<'a>

struct Foo<'a> {s: &'a str}

impl<'a> Foo<'a> {
    fn foo(&'a self) -> &'a str {. // <---- this is the line in question
        self.s
    }
}

fn main() {
   let f: Foo<'static> = Foo{s:"123"} ;
   {
       let bf = &f;
       let s = bf.foo();
   }
}

play.rust-lang.org

Rust Playground

A browser interface to the Rust compiler to experiment with the language

The function foo signature should be fn foo(&self) -> &str {. I don't understand why the borrow checker is ok with fn foo(&'a self) -> &'a str {.

My understanding of lifetime is that they are types (with subtyping and variance). Here self is of type Foo<'static>. foo should not accept any reference with a shorter lifetime than 'static, based on how the code is written. But why bf, a non-static-lifetime reference, can still call foo?

1 post - 1 participant

Read full topic

Source: View source

PressRex profile image
by PressRex

Subscribe to New Posts

Lorem ultrices malesuada sapien amet pulvinar quis. Feugiat etiam ullamcorper pharetra vitae nibh enim vel.

Success! Now Check Your Email

To complete Subscribe, click the confirmation link in your inbox. If it doesn’t arrive within 3 minutes, check your spam folder.

Ok, Thanks

Read More