生存期如何处理常量字符串/字符串文字? [英] How does the lifetime work on constant strings / string literals?

查看:58
本文介绍了生存期如何处理常量字符串/字符串文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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[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"
}

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

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

推荐答案

终身淘汰推断出

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

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

这基本上意味着get_str的返回值必须有效,只要s有效. 字符串文字"Hello world"&'static str ,表示它在程序的整个运行过程中均有效.由于这满足了函数签名中的生命周期约束(因为对于任何'a'static始终包含'a),因此可以正常工作.

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"
}

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

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. 可以是'static,如您的示例所示,或者
  2. 返回值的生存期必须与参数的生存期相关联,这是生存期省略默认设置的内容.
  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.

这篇关于生存期如何处理常量字符串/字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆