6 ms·
Type alias impl trait [0]. Async fns return an existential type `impl Future`. You cannot return that type in traits yet (on stable), so getting a concrete retu
by ibraheemdev 5y ago
Type alias impl trait [0]. Async fns return an existential type `impl Future`. You cannot return that type in traits yet (on stable), so getting a concrete return type requires dynamic dispatch and a heap allocation. On top of that, async fns capture from any references they take as arguments. To do that in traits would require GATs (generic associated types) [1]:
impl Foo for Bar {
// GAT ↓ TiiT ↓
type Output<'a> = impl Future<Output = Foo> + 'a;
fn foo<'a>(&'a self) -> Self::Output<'a> { ... }
}
The above is possible on nightly, whereas on stable you would have to box the future, and because you can't capture from self, you would have to use a ref counted pointer or clone the parts of self you need. Eventually, this entire transformation would allow for async fns directly in traits, but that is probably a long way off [2].
[0]: https://github.com/rust-lang/rust/issues/63063 https://github.com/rust-lang/rust/issues/63063
[1]: https://github.com/rust-lang/rust/issues/44265 https://github.com/rust-lang/rust/issues/44265
[2]: http://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/ http://smallcultfollowing.com/babysteps/blog/2019/10/26/asyn...