gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:25:49 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com