What Are Existential Types in Rust (impl Trait in Type Position)?

Existential types (impl Trait in type position) let Rust hide a concrete type behind a trait requirement, enforcing behavior without exposing the specific implementation.

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.