如何解决为什么此迭代器需要使用期限,如何给它一个生命期?
我正在尝试编译以下内容:
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://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 {
我怀疑我在这里误解了迭代器的某些关键方面。有什么建议吗?
解决方法
我通过在两个迭代器中都添加+ 'a
来解决此问题:
fn read<'a>(tokens: impl Iterator<Item=&'a str> + 'a) -> impl Iterator<Item=String> + 'a {
tokens.map(|t| t.to_owned())
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。