string - 生命周期如何作用于常量字符串/字符串文字?

标签 string rust lifetime string-literals

我读了tutorial on the official website我对常量字符串/字符串文字的生命周期有一些疑问。

当我编写以下代码时出现错误:

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

错误:

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

但是当我添加参数时就可以了:

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

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

最佳答案

Lifetime elision推断完整类型的

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

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

这基本上意味着只要 s 有效,get_str 的返回值就必须有效。 string literal "Hello world" is &'static str 的实际类型,这意味着它在程序的整个运行过程中都有效。由于这满足了函数签名中的生命周期限制(因为 'static 总是包含 'a 用于任何 'a),所以这是可行的。

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

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

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

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

  1. 它可以是'static,就像在您的示例中一样,或者
  2. 返回值的生命周期必须与参数的生命周期相关联,这是生命周期省略的默认设置。

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

关于string - 生命周期如何作用于常量字符串/字符串文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361045/

相关文章:

c - 如何只打印文件名

c++ - std::string::append(std::string) 错误输出

c# - 在 C# 中替换同时包含波斯语和英语字母的字符串

multithreading - 在线程之间传递 hashmap 的 channel |陷入循环 | rust

rust - warp (Rust) 中的 API key 验证

opengl - 为什么顶点位置是从颜色缓冲区而不是位置缓冲区中获取的?

rust - 如何根据编译功能标志为枚举添加生命周期

javascript - 从字符串列表中删除前缀

generics - 当泛型类型受到泛型生存期的限制时,这意味着什么?

rust - 我如何弄清楚命名生命的来源?