Reputation: 13
why fn return &str should static lifetime, but struct's fn not?
fn say() -> &str {
"this is str"
}
// consider using the `'static` lifetime: `&'static `
but cat.hi ,is correct
struct Cat {}
impl Cat {
fn hi(&self) -> &str {
"hi"
}
}
why fn return &str tips consider using the 'static
lifetime: &'static
, but struct fn not?
Upvotes: 1
Views: 90
Reputation: 1858
In general every reference needs a lifetime. The compiler will autocomplete them in some cases. These cases are described here https://doc.rust-lang.org/nomicon/lifetime-elision.html.
There is no rule for the first example, so you have to provide a lifetime.
In your second example the rule If there are multiple input lifetime positions, but one of them is &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.
is applied which makes it to
struct Cat {}
impl Cat {
fn hi<'a>(&'a self) -> &'a str {
"hi"
}
}
Which is actually different from
struct Cat {}
impl Cat {
fn hi<'a>(&'a self) -> &'static str {
"hi"
}
}
Upvotes: 3