为什么这段代码会编译?
fn get_iter() -> impl Iterator<Item = i32> {
[1, 2, 3].iter().map(|&i| i)
}
fn main() {
let _it = get_iter();
}
Run Code Online (Sandbox Code Playgroud)
[1, 2, 3]是一个局部变量并iter()借用它.此代码不应编译,因为返回的值包含对局部变量的引用.
我在官方网站上阅读了教程,我对常量字符串/字符串文字的生命周期有一些疑问.
我编写以下代码时出错:
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,即使它与它无关 …