0
fn my_fun<'a>(r: &'a i32) -> &'a i32 {
    if *r > 5 {
        r
    } else {
        &5
    }
}

fn main() {
    let result;
    {
        result = my_fun(&111); 
    }
    println!("result: {}", result);
}

I expected the compile error but it works good.

What is the lifetime of &111 in the example above?

hanmomhanda
  • 305
  • 1
  • 2
  • 15
  • TL;DR the duplicate: `'static` – Shepmaster Apr 21 '19 at 01:30
  • Thanks. But a little different thing is that `my_fun` has a lifetime parameter `'a` in the result type, not `'static`. How can `my_fun` return a static reference even though it has `'a` as a lifetime parameter in the result type? `'a` can include `'static`? – hanmomhanda Apr 21 '19 at 02:08
  • 1
    `'a` is a generic lifetime that will be replaced by whatever concrete lifetime is in use. `&111` always generates a `&'static i32`, so `'a` is `'static` for this call. Just like if you had `foo(_: T)` and called it with `foo(true)` — `T` is `bool` for that call. – Shepmaster Apr 21 '19 at 02:19
  • 1
    Oh, I thought `'a`' can not be a `'static` because there exists the `'static` as a separate keyword. Thanks for the quick and kind answer. Now it's clear! – hanmomhanda Apr 21 '19 at 02:27
  • @Shepmaster Can I ask one more thing? `'a` can include `'static` only when used in return type? In below code, the lifetime parameter is used in the input param, not return type, and the code does not compile. ``` static mut GLOBAL: &i32 = &111; static STATIC: &i32 = &222; fn my_fun<'a>(r: &'a i32) { GLOBAL = r; } fn main() { my_fun(STATIC); } ``` – hanmomhanda Apr 21 '19 at 13:04
  • That's because each function is checked independently, regardless of how it is called. Using `'a` in `my_fun` means that *any* lifetime might be passed, including those that are not `'static`. Those can never compile, so the program is invalid. Also, it's a **really bad idea** to use `static mut` — so much that it's been considered removing them from the language. – Shepmaster Apr 21 '19 at 13:25

0 Answers0