Existential types in Rust, written as impl Trait in type position, allow you to declare a variable that holds a single, unknown concrete type that implements a specific trait, without naming that type. This feature, introduced in Rust 1.65, is primarily used in struct fields and return types to hide implementation details while enforcing a behavioral contract.
struct Handler {
// The compiler picks one concrete type for this field
callback: impl Fn(i32) -> i32,
}
fn make_handler() -> impl Fn(i32) -> i32 {
|x| x * 2
}
Note: impl Trait in type position is distinct from dyn Trait (trait objects), which allows for multiple different types in a collection via dynamic dispatch.