且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

生命周期如何处理常量字符串/字符串文字?

更新时间:2023-11-05 23:50:28

生命周期省略 推断

的完整类型
fn get_str(s: &str) ->&str

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

这基本上意味着只要 s 有效,get_str 的返回值就必须有效.字符串文字的实际类型"Hello world"&'static str,表示它对程序的整个运行都是有效的.由于这满足函数签名中的生命周期约束(因为对于任何 'a'static 总是包含 'a),所以这是有效的.>

然而,让您的原始代码工作的更明智的方法是为函数类型添加显式生命周期:

fn get_str() ->&'static str {你好世界"}

Hello World"怎么从参数s中借用了,甚至与s无关?

只有两个选项对具有单个引用参数的函数中的返回值的生命周期有意义:

  1. 它可以是 'static,在你的例子中应该是这样,或者
  2. 返回值的生命周期必须与参数的生命周期相关联,这是生命周期省略的默认值.

在本文顶部的链接中选择后者是有一些理由的,但基本上归结为后者是更常见的情况.请注意,生命周期省略根本不看函数体,它只看函数签名.这就是为什么它不会考虑您只是返回一个字符串常量这一事实.

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?

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.