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

Ada*_*dam 4 string lifetime string-literals rust

在官方网站上阅读了教程,我对常量字符串/字符串文字的生命周期有一些疑问.

我编写以下代码时出错:

fn get_str() -> &str {
    "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

但是添加参数时没关系:

fn get_str(s: &str) -> &str {
    "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

为什么这样做?如何"Hello World"借用参数s,即使它与它无关s

fjh*_*fjh 10

终身省略推断完全类型

fn get_str(s: &str) -> &str
Run Code Online (Sandbox Code Playgroud)

fn get_str<'a>(s: &'a str) -> &'a str
Run Code Online (Sandbox Code Playgroud)

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

但是,让原始代码工作的更合理的方法是为函数类型添加显式生存期:

fn get_str() -> &'static str {
    "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

"Hello World"如何从参数中借用s,即使它与之无关s

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

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

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