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

女生的网名这么多〃 提交于 2019-11-26 10:03:36

问题


I read the tutorial on the official website and I have some questions on the lifetime of constant strings / string literals.

I get an error when I write the following code:

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

error:

error[E0106]: missing lifetime specifier
 --> src/main.rs:1:17
  |
1 | fn get_str() -> &str {
  |                 ^ expected lifetime parameter
  |
  = help: this function\'s return type contains a borrowed value, but there is no value for it to be borrowed from
  = help: consider giving it a \'static lifetime

However it\'s OK when I add a parameter:

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

Why does this work? How does \"Hello World\" borrow from the parameter s, even it though it has nothing to do with s?


回答1:


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.



来源:https://stackoverflow.com/questions/31230585/how-does-the-lifetime-work-on-constant-strings-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!