rust - 为什么这个迭代器需要一个生命周期,我该如何给它一个生命周期?

标签 rust iterator lifetime

我正在尝试编译以下内容:

fn read<'a>(tokens: impl Iterator<Item=&'a str>) -> impl Iterator<Item=String> {
  tokens.map(|t| t.to_owned())
}
error[E0482]: lifetime of return value does not outlive the function call
 --> src/lib.rs:1:53
  |
1 | fn read<'a>(tokens: impl Iterator<Item=&'a str>) -> impl Iterator<Item=String> {
  |                                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
note: the return value is only valid for the lifetime `'a` as defined on the function body at 1:9
 --> src/lib.rs:1:9
  |
1 | fn read<'a>(tokens: impl Iterator<Item=&'a str>) -> impl Iterator<Item=String> {
  |         ^^

Playground 链接:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=55460a8b17ff10e30b56a9142338ec19

令我感到奇怪的是返回值与生命周期有关;它的内容被拥有并直接向外传递。

我看到这篇博文:https://blog.katona.me/2019/12/29/Rust-Lifetimes-and-Iterators/

但这些都不起作用:

fn read<'a>(tokens: impl Iterator<Item=&'a str>) -> impl Iterator<Item=String> + '_ {
fn read<'a>(tokens: impl Iterator<Item=&'a str>) -> impl Iterator<Item=String> + 'a {

我怀疑我在这里误解了迭代器的一些关键方面。有什么建议吗?

最佳答案

我通过向 both 迭代器添加 + 'a 解决了这个问题:

fn read<'a>(tokens: impl Iterator<Item=&'a str> + 'a) -> impl Iterator<Item=String> + 'a {
  tokens.map(|t| t.to_owned())
}

关于rust - 为什么这个迭代器需要一个生命周期,我该如何给它一个生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63608083/

相关文章:

macros - 如何匹配宏中的特征边界?

rust - 如何在异步函数中设置断点?

enums - 为什么使一个枚举变体成为 `f64` 会增加此枚举的大小?

java - 为什么这里没有抛出 ConcurrentModificationException ?

rust - 如何使用 Rust 中的 StreamExt::scan 方法改变异步 block 内的状态?

rust - 启用项目功能时启用 Rust nightly 功能

mysql - 迭代游标后从 MySQL 函数返回值

rust - 实现不消耗的迭代器

rust - 值(value)的生命周期与借用的生命周期

asp.net - 在统一配置部分与通用生命周期管理器一起工作