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();
}
}
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
Source: View source