rust - 为什么我可以在没有生命周期问题的情况下内联调用 iter 和 collect?

标签 rust borrow-checker

为什么我可以毫无问题地运行以下语句?

println!("{:?}", (vec!["1".to_string(), "1".to_string(), "1".to_string()]).iter().collect::<Vec<&String>>());

如果我理解正确的话,它会创建一个拥有的字符串数组,获取一个字符串引用的迭代器,然后收集一个字符串引用数组。但是这些引用引用了一个数组,该数组在该语句的开头不再存在。为什么有效?

最佳答案

生命周期延长到statement结束(即分号),而不是 .iter() 的末尾。

当您将此代码拆分为两个语句时,编译器会对此进行解释。

the Rust Reference我们发现:

Apart from lifetime extension, the temporary scope of an expression is the smallest scope that contains the expression and is one of the following:

  • The entire function body.
  • A statement.
  • The body of an if, while or loop expression.
  • The else block of an if expression.
  • The condition expression of an if or while expression, or a match guard.
  • The expression for a match arm.
  • The second operand of a lazy boolean expression.

在这种情况下,最小范围是语句。

fn main() {
    let v = (vec!["1".to_string(), "1".to_string(), "1".to_string()])
        .iter()
        .collect::<Vec<&String>>(); // !!! ERROR
    println!("{:?}", v);
}
...
4 |         .collect::<Vec<&String>>();
  |                                   - temporary value is freed at the end of this statement
...

关于rust - 为什么我可以在没有生命周期问题的情况下内联调用 iter 和 collect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75041582/

相关文章:

math - 正弦函数在哪里?

rust - 在 Rust 中存储具有泛型类型参数的异构类型集合

rust - 预期为 i32,找到类型参数,但类型参数为 i32

rust - 借来的值(value)在 Tokio 的 future 中存在的时间不够长

rust - 由于生命周期/借用错误,文本文件解析函数无法编译

linker - 通过使用内联汇编的 Raspberry Pi3 的 Rust 启动代码

rust - 遇到正确的设计模式

iterator - 如何使用生命周期嵌套可变访问?

rust - 为什么从 Rust 中的函数返回一个 &[u8] 而不是 u8 借用自己?

multithreading - 借用检查器可以知道 Arc 何时为 "released"吗?可以暂时授予“静态生命周期”吗?