我有以下设置,我试图创建一个Dummy
future,它旨在修改future中从f: FnMut(&mut i32) -> Fut
获得的值。我传递泛型函数fun
来替换它,但我得到了不同的生存期。
#![allow(unused_variables)]
pub struct Dummy<Fut, F> {
f: F,
futures: futures::stream::FuturesUnordered<Fut>
}
impl<Fut, F> Dummy<Fut, F>
where
F: FnMut(&mut i32) -> Fut,
Fut: futures::Future<Output = ()>,
{
fn new(f: F) -> Self {
Self {
f,
futures: futures::stream::FuturesUnordered::new()
}
}
}
impl<Fut, F> futures::Future for Dummy<Fut, F>
where
F: FnMut(&mut i32) -> Fut,
Fut: futures::Future<Output = ()>
{
type Output = ();
fn poll(self: core::pin::Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> core::task::Poll<()> {
// logic emitted
core::task::Poll::Ready(())
}
}
fn fun<'a>(f: &'a mut i32) -> impl futures::Future<Output = ()> + 'a {
async move {
*f += 1;
}
}
#[tokio::main]
async fn main() {
Dummy::new(fun).await;
}
playground link
它给出了编译错误:
error[E0308]: mismatched types
--> src/main.rs:45:20
|
45 | Dummy::new(fun).await;
| ^^^^^^ one type is more general than the other
|
= note: expected trait `for<'r> FnOnce<(&'r mut i32,)>`
found trait `for<'a> FnOnce<(&'a mut i32,)>`
= note: the lifetime requirement is introduced here
error[E0308]: mismatched types
--> src/main.rs:45:20
|
45 | Dummy::new(fun).await;
| ^^^^^^ one type is more general than the other
|
= note: expected trait `for<'r> FnOnce<(&'r mut i32,)>`
found trait `for<'a> FnOnce<(&'a mut i32,)>`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to 4 previous errors
有没有可能以一种消除这些不匹配类型错误的方式来注解impl
?我可以用'static
来注解所有内容,就像我在这里所做的那样:playground link。但我试图避免这种解决方案,因为我想在未来的poll
方法中相互借用相关数据。
1条答案
按热度按时间k5ifujac1#
fun()
的签名将引用的生存期与它返回的将来的生存期连接起来。您需要在Dummy
的Future
实现上指定相同类型的连接:Playground