Resolved: why fn return &str, consider using the `’static` lifetime: `&’static `, but struct fn is correct?

Question:

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?

Answer:

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"
    }
}

If you have better answer, please add a comment about this, thank you!

If you like this answer, you can give me a coffee by <a href=”https://violencegloss.com/mkw7pgdwwr?key=2a96ade6f3760c7e63343a320febb78e”>click here</a>

Source: Stackoverflow.com