rust - 为什么这个迭代器需要一个生命周期,我该如何给它一个生命周期?
问题描述
我正在尝试编译以下内容:
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> {
| ^^
令我感到奇怪的是,返回值完全与生命周期有关。它的内容是拥有并直接向外传递的。
我看到了这篇博文: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 {
我怀疑我在这里误解了迭代器的一些关键方面。有什么建议么?
解决方案
我通过添加两个迭代器+ 'a
来解决它:
fn read<'a>(tokens: impl Iterator<Item=&'a str> + 'a) -> impl Iterator<Item=String> + 'a {
tokens.map(|t| t.to_owned())
}
推荐阅读
- blockchain - 从 r3 corda 应用程序从 v4.3 逐步升级到 4.4
- javascript - 执行块后捕获 Firebase 创建用户错误
- kubernetes - 为什么我的 MongoDB 部署会破坏 minikube(E0413,空 IP)?
- elasticsearch - 如何使用除“_id”之外的任何其他键批量更新弹性搜索文档?
- android - 如何自定义 Android BLE(蓝牙低功耗)gatt 传输速度?
- confluence - confluence wiki API 删除附件
- c++ - 从 string 到 const wchar_t* 的类型转换。类型不匹配
- java - Spring @Component 创建顺序
- reactjs - 在客户端和服务器之间共享 GraphQL 模式
- mysql - 如何避免 MySQL 中 where 子句中的语句重复?