gpt4 book ai didi

rust - 引用内部闭包的迭代器的智能构造函数

转载 作者:行者123 更新时间:2023-11-29 08:29:30 24 4
gpt4 key购买 nike

考虑以下用于(大大简化的)迭代器的代码,其中包含对内部闭包的引用:

struct IteratorState<'a, T: 'a + Fn(i32) -> i32> {
closure: &'a T,
}

impl<'a, T: 'a + Fn(i32) -> i32> Iterator for IteratorState<'a, T> {
type Item = i32;

fn next(&mut self) -> Option<i32> {
None
}
}

它编译并且我可以直接构建IteratorState。但是,我还需要一个智能构造函数来隐藏一些实现细节(MCVE 中未显示)。以下尝试无法编译:

fn mk_iter<'a, T: Fn(i32) -> i32>(closure: &'a T) -> impl Iterator<Item = i32> {
IteratorState { closure }
}

The error is

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/lib.rs:14:5
|
14 | IteratorState { closure }
| ^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime 'a as defined on the function body at 13:1...
--> src/lib.rs:13:1
|
13 | fn mk_iter<'a, T: Fn(i32) -> i32>(closure: &'a T) -> impl Iterator<Item = i32> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:14:21
|
14 | IteratorState { closure }
| ^^^^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that return value is valid for the call
--> src/lib.rs:13:54
|
13 | fn mk_iter<'a, T: Fn(i32) -> i32>(closure: &'a T) -> impl Iterator<Item = i32> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^

我想我明白问题是什么:不能保证构造的 IteratorState 不会比包含的引用更有效(如果我弄错了请纠正我),但我不太确定如何修复它。

最佳答案

impl Trait 语法支持为返回类型添加生命周期:

fn mk_iter<'a, T: Fn(i32) -> i32>(closure: &'a T) -> impl Iterator<Item = i32> + 'a {
// here ^^^^
IteratorState {
closure
}
}

( link to playground )

关于rust - 引用内部闭包的迭代器的智能构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52025655/

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