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
?
在具有单个引用参数的函数中,返回值的生命周期只有两个选项:
'static
应该是,在你的例子中,或者在本文顶部的链接中选择后者有一些理由,但它基本上归结为后者是更常见的情况.请注意,life elision 根本不会查看函数体,它只是通过函数签名.这就是为什么它不会考虑你只是返回一个字符串常量的事实.