How does a lifetime job work with constant strings?

I have read the tutorial on the official site and I have some questions about the lifetime of constant strings.

I am getting an error while writing the following code:

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

      

Mistake:

test.rs:1:17: 1:21 error: missing lifetime specifier [E0106]
test.rs:1 fn get_str() -> &str {
                          ^~~~
test.rs:1:17: 1:21 help: run `rustc --explain E0106` to see a detailed explanation
test.rs:1:17: 1:21 help: this function return type contains a borrowed value, but there is no value for it to be borrowed from
test.rs:1:17: 1:21 help: consider giving it a 'static lifetime
error: aborting due to previous error

      

However, this is ok when I add the parameter:

fn get_str(s: &str) -> &str {
    "Hello World"
}

      

Why does it work? How to "Hello World"

borrow from a parameter s

even if it has nothing to do with 's'?

+3


source to share


1 answer


Lifetime elision reports that the complete type

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

      

is an

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

      

which basically means the return value get_str

should be valid as long as s

valid. The actual type of the string constant "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 (since it 'static

always includes 'a

for anyone 'a

), it works.

However, a smarter way to make your original code 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 's' even if it has nothing to do with 's'?

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

  • It could be 'static

    as it should be in your example, or
  • The lifetime of the return value must be tied to the lifetime of the argument, to which the default elision is used by default.

There is some justification for choosing the latter in the link at the top of this post, but it basically boils down to the latter being a much more common case. Note that the lifetime exception doesn't look at the function body at all, it just goes under the function sign. Therefore, you shouldn't take into account the fact that you are just returning a string constant.

+7


source







All Articles