How does the lifetime work on constant strings / string literals?

Lifetime elision infers that the full type of

fn get_str(s: &str) -> &str

is

fn get_str<'a>(s: &'a str) -> &'a str

which basically means that the return value of get_str has to be valid as long as s is valid. The actual type of the string literal "Hello world" is &'static str, which means that it is valid for the entire run of the program. Since this satisfies the lifetime constraints in the function signature (because 'static always includes 'a for any 'a), this works.

However, a more sensible way to get your original code to work would be to add an explicit lifetime to the function type:

fn get_str() -> &'static str {
    "Hello World"
}

How does “Hello World” borrow from the parameter s, even it has nothing to do with s?

There are only two options that would make sense for the return value’s lifetime in a function with a single reference argument:

  1. It can be 'static, as it should be in your example, or
  2. The return value’s lifetime has to be tied to the lifetime of the argument, which is what lifetime elision defaults to.

There is some rationale for choosing the latter in the link at the top of this post, but it basically comes down to the fact that the latter is the far more common case. Note that lifetime elision does not look at the function body at all, it just goes by the function signature. That’s why it won’t take the fact that you’re just returning a string constant into account.

Leave a Comment