我读了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"如何从参数sborrow ,即使它与s无关?

推荐答案

Lifetime el是ion表示

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

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 是 valid. The actual type of the string literal "Hello world"&'static str, which means that it 是 valid for the entire run of the program. Since th是 sat是fies the lifetime constraints in the function signature (because 'static always includes 'a for any 'a), th是 works.

但是,让原始代码正常工作的一种更明智的方法是向函数类型添加显式生存期:

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

"Hello World"如何borrow 参数s,即使它与s无关?

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

  1. 它可以是'static,就像你的例子中应该的那样,或者
  2. The return value's lifetime has to be tied to the lifetime of the argument, which 是 what lifetime el是ion defaults to.

There 是 some rationale for choosing the latter in the link at the top of th是 post, but it basically comes down to the fact that the latter 是 the far more common case. Note that lifetime el是ion 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.

Rust相关问答推荐

为什么我们不能通过指针算法将Rust原始指针指向任意地址?'

Arrow RecordBatch as Polars DataFrame

使用pyo3::Types::PyIterator的无限内存使用量

当rust中不存在文件或目录时,std::FS::File::Create().unwire()会抛出错误

异步FN中的 rust 递归

铁 rust 中的共享对象实现特征

我应该将哪些文件放入我的GitHub存储库

不能在Rust中使用OpenGL绘制三角形

为什么&;mut buf[0..buf.len()]会触发一个可变/不可变的borrow 错误?

Rust 如何返回大类型(优化前)?

当没有实际结果时,如何在 Rust 中强制执行错误处理?

如何获取模块树?

缺失serde的字段无法设置为默认值

为什么不能在 Rust 中声明静态或常量 std::path::Path 对象?

Rust 中的生命周期:borrow 的 mut 数据

将 Futures 的生命周期特征绑定到 fn 参数

将 `&T` 转换为新类型 `&N`

在 Rust 中如何将值推送到枚举 struct 内的 vec?

您如何使用枚举反序列化字符串,其中任何其他值反序列化为新类型变体同时保留字符串?

如果我立即等待,为什么 `tokio::spawn` 需要一个 `'static` 生命周期?