我阅读了官方网站上的教程,对于常量字符串/字符串字面值的生命周期有一些疑问。
当我编写以下代码时,会出现错误:
错误:
这为什么有效?即使与参数无关,的特性?
当我编写以下代码时,会出现错误:
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"
如何借用