这段奇怪的代码会发出do_the_thing()
的错误,表示T
的生命周期 不够长:
use std::future::Future;
trait Connection: Send {
type ExecFut<'a>: Future<Output = ()> + Send
where
Self: 'a;
fn transaction<F>(&mut self, _f: F)
where
F: for<'a> FnOnce(&'a mut Self) -> Box<dyn Future<Output = ()> + Send + 'a> + Send,
{
unimplemented!()
}
fn execute<'a>(&'a mut self) -> Self::ExecFut<'a> {
unimplemented!()
}
}
fn do_the_thing<T: Connection>(connection: &mut T) {
connection.transaction(|conn| {
Box::new(async move {
conn.execute().await;
})
});
}
error[E0310]: the parameter type `T` may not live long enough
--> src/main.rs:22:9
|
22 | / Box::new(async move {
23 | | conn.execute().await;
24 | | })
| |__________^ ...so that the type `T` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound...
|
20 | fn do_the_thing<T: Connection + 'static>(connection: &mut T) {
| +++++++++
在playground号公路上可以看到.
就我所知,不应隐含要求'static
英镑的界限.几乎一切都受到'a
的限制,T
的任何生命周期 都应该总是超过它的生命周期 .尽管很明显我可能遗漏了一些东西.
我还发现了一些没有帮助的"解决方案":
- 按照编译器的建议增加
'static
是不合理的.它是可以解决的,但我想使用的是真正的Connection
,生命周期 不是'static
. - 出于某种原因,删除
dyn Future
上的Send
界限会使其通过编译.这对我来说毫无意义. - 如果我使函数是非泛型的,但使用的是
Connection
而不是'static
,它也会编译,这似乎与编译器错误相矛盾.
以上不是真正的代码;最初的动机源于使用diesel-async箱中的AsyncConnection
和类似的代码 struct .然而,我希望它代表核心问题,并希望通过了解这里的问题和潜在的解决办法,它们能够得到调整.