Existential Types in Rust
a year ago
- #Type Systems
- #Rust
- #Async Programming
- Rust has been working on adding explicit existential types since 2017, which are types that exist but cannot be directly manipulated outside their scope.
- Existential types invert the control of generic types, letting the function decide the concrete type while the caller treats it as unknown.
- Rust currently has a limited form of existential types called `impl Trait`, which allows functions to return types implementing a trait without specifying the concrete type.
- `impl Trait` is useful for abstracting API details without runtime indirection, especially in asynchronous functions and closures.
- Rust 1.75 (December 2023) allowed `impl Trait` as return values from trait methods, but they still have limitations compared to full existential types.
- Future improvements aim to allow existential types in type aliases and structures, enabling patterns like guaranteed same-type returns across functions.
- Existential types would improve ergonomics in asynchronous programming, a focus for Rust 2024, by allowing `impl Future` values to be stored in structures.