相关疑难解决方法(0)

为什么我可以返回对本地文字但不是变量的引用?

为什么这段代码会编译?

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()借用它.此代码不应编译,因为返回的值包含对局部变量的引用.

reference rust borrow-checker

18
推荐指数
1
解决办法
1094
查看次数

生命周期如何处理常量字符串/字符串文字?

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

我编写以下代码时出错:

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,即使它与它无关 …

string lifetime string-literals rust

4
推荐指数
1
解决办法
1737
查看次数