How can I name the type returned by a function for use in a struct field?
⚓ Rust 📅 2026-03-10 👤 surdeus 👁️ 1Let's say I have this trait for something that can be called serially to do async work:
trait Frobnicator {
fn frobnicate(&mut self) -> impl Future<Output = ()>;
}
This is not dyn compatible, because it returns an arbitrary future type. I can make it dyn compatible by having it return Box<impl Future<Output = ()>, but that throws away an optimization opportunity—because it's only called serially, a dyn-compatible implementation could provide internal storage for the future that is reused with each call. Something like this:
trait ErasedFrobnicator {
fn frobnicate_erased(&mut self) -> Pin<&mut impl Future<Output = ()>>;
}
Here's the problem though: in order to provide that storage, I need to name the future's type. In an unholy mix of Rust and C++ I could do this using decltype:
struct FrobnicatorView<F: Frobnicator>(
F, MaybeUninit<decltype(declval<F>().frobnicate())>);
impl ErasedFrobnicator for FrobnicatorView {
// ...
}
But of course decltype doesn't exist. So is there any trick to refer to the name of the future type returned by <F as Frobnicator>::frobnicate in order to provide a field like this? I could also have Frobnicator provide an associated type for this, but that makes implementing Frobnicator inconvenient because implementors can no longer use async fn (otherwise they would have the same naming problem over again) .
5 posts - 3 participants
🏷️ Rust_feed