<p>I am investigating ways to add some form of <em>abstract data types</em> to a toy language.</p>
<p>I was reading Graydon Hoare's <a href="https://graydon2.dreamwidth.org/307291.html" rel="nofollow noreferrer">The Rust I Wanted Had No Future</a>, in which he talks about <a href="https://en.wikipedia.org/wiki/Type_system#Existential_types" rel="nofollow noreferrer">existential types</a>. I have not used a language with existentials, but he seem to write about them as an alternative to traits, as a way to have <em>abstract data types</em>.</p>
<p>He writes this about traits:</p>
<blockquote>
<p><strong>Traits.</strong> I generally don't like traits / typeclasses. To my eyes they're too type-directed, too global, too much like programming and debugging a distributed set of invisible inference rules, and produce too much coupling between libraries in terms of what is or isn't allowed to maintain coherence.</p>
</blockquote>
<p>And about existentials:</p>
<blockquote>
<p><strong>Underpowered existentials.</strong> The <code>dyn Trait</code> mechanism in Rust allows runtime and heterogeneous polymorphism, a.k.a. Existentials. These types are useful for many reasons: both solving heterogeneous representation cases and also selectively backing-off from monomorphization or inlining (when you have those) in order to favour code size / compile time or allow dynamic linking or runtime extension.</p>
</blockquote>
<p>He also notes existentials in the section about <em>Missing Errors</em>:</p>
<blockquote>
<p>the <code>throws</code> syntax, the dedicated error-carrying ABI, and the not-necessarily-allocating existential Error type in Swift would have all helped to fill in this &quot;explicit error union&quot; model.</p>
</blockquote>
<p>I get the impression that existentials are more like <a href="https://en.wikipedia.org/wiki/Go_(programming_language)#Interface_system" rel="nofollow noreferrer">Interfaces in Go</a> ─ that is, structural, as opposed to nominal. Traits in Rust are more powerful, and can contain default implementations for methods as well as act as <em>trait bounds</em> on generics.</p>
<p>How are existentials different from Rust's traits?</p>

<types><rust><traits><interfaces><existential-types>
How are existential types different from Rust's traits?
CC BY-SA 4.0
2024-11-30T11:17:05.307Z
If you have ever used a “dynamically-typed” language, you *have* used a language with existentials. A “dynamic type” is just $\sum_{T:\mathsf{type}} T$, which is an existential.
user3840170
<p>You seem to have misunderstood the blog post. Existentials aren't an alternative to traits, and existentials aren't comparable with traits. It's a category error.</p>
<p>Rust does have existentials! <code>dyn Trait</code> &quot;trait objects&quot; and <code>impl Trait</code> &quot;abstract types&quot; <em>are</em> its notion of existential type. Compare <a href="https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/existential_quantification.html" rel="nofollow noreferrer">GHC's <code>ExistentialQuantification</code> extension</a>:</p>
<pre class="lang-rust prettyprint-override"><code>dyn Trait
</code></pre>
<pre class="lang-hs prettyprint-override"><code>forall a. Typeclass a =&gt; a
</code></pre>
<p>Hoare is merely complaining that <code>dyn</code> and <code>impl</code> are underpowered and underutilized/overly discouraged. This has nothing to do with his personal distaste for the trait system itself and for typeclass systems in general.</p>
<p>(A better Rust programmer than I may be able to elucidate his complaint about Rust's existentials in more detail--though I do notice that one lacking feature is the ability to existentially quantify generic type <em>variables</em>--but I believe this answers your question.)</p>

CC BY-SA 4.0
2024-10-23T01:51:39.103Z
2024-10-23T15:01:06.763Z
2024-10-23T15:01:06.763Z
Unrelated String
CC BY-SA 4.0
2024-10-23T06:44:04.967Z
Note that Rust's `impl Trait` syntax is sometimes also described as an "existential type," and it does have many seemingly arbitrary restrictions on where it may appear.
Kevin
CC BY-SA 4.0
2024-10-23T12:28:38.527Z
@Kevin: Most restrictions on where `impl Trait` may appear are "temporary", there is a will to lift them, but it requires significant engineering effort, and thus will take time.
Matthieu M.
<h2>You can encode traits as existentials, but I don't think this approach is helpful whatsoever</h2>
<p>The canonical example for existential types are ML modules (note however that OCaml extensions to ML-type module systems extend it beyond existential types), and traits/type classes are <em>somehow</em> similar to ML modules, but with a few important differences.</p>
<p>Consider this ML (OCaml) code:</p>
<pre class="lang-none prettyprint-override"><code>module type Ord =
  sig
    type 'a 
    val leq : 'a -&gt; 'a -&gt; bool
  end
</code></pre>
<p>This is an existential type: it could be written as <span class="math-container">$\exists \tau. \tau \rightarrow \tau \rightarrow \mathbf{2}$</span>. <span class="math-container">$\tau$</span> is an abstract type</p>
<p>Now, there are two ways we could use this type:</p>
<ul>
<li>given a function of type that can be written as <span class="math-container">$\alpha \to \alpha \to \mathbf{2}$</span> (where <span class="math-container">$\alpha$</span> is a type variable), i.e. fulfills the existential type, we may <strong>pack</strong> this value into a module such that it has existential type (i.e., <span class="math-container">$\alpha$</span> is now abstract and invisible)</li>
<li>given a value of this type (i.e., a module satisfying the signature <code>Ord</code>), we can <strong>unpack</strong> this value to use the value (in this case, the function <span class="math-container">$\leq$</span>) abstracted within the module, without the programmer needing to know the implementation.</li>
</ul>
<p>For example, if I'm writing a red-black tree, all I need to know is that the keys are comparable with each other. In the case of string, there may be many reasonable ways to compare them: e.g. in lexicographic order, by length, or otherwise. I don't need to know how it is implemented, yet I can still write code that is correct with regard to the implementation (and, in fact, all correct implementations).</p>
<p>A trait or type class is basically like a signature, except there could be only one instance (implementation). I can write something similar in Haskell:</p>
<pre class="lang-none prettyprint-override"><code>class Ord a where
  (&lt;=) :: a -&gt; a -&gt; Bool
</code></pre>
<p>It looks similar to a ML signature, right? But there could only be one instance of <code>Ord a</code> for each <code>a</code>! (There are some GHC extensions that allow one to violate this rule, but even if you have multiple, you don't get to choose which yourself, so this is generally considered bad practice.)</p>
<p>So it doesn't really have the same expressive power as ML modules and signatures. Existential types expand the expressive power of ML (i.e., allow previously unexpressible programs to be expressible), but type classes don't really. They can be thought of and implemented as a form of search and record passing: i.e., whenever you write &lt;=, the compiler determines the type of the arguments (say T), search the type class database for an implementation of <code>Ord</code> for <code>T</code> (which is encoded as a record), and implicitly passes the record to your function. While it is more hands-off and automatic than modules and existentials, it does not provide the same level of expressive power that modules do. You won't be able to reasonably implement a counter, for example, using type classes.</p>
<p>So while it is possible to think of them as existentials, it is best not to, as it lacks the expressiveness of existentials.</p>
<p>Recently, there has been a line of work in OCaml, <a href="https://www.cl.cam.ac.uk/%7Ejdy22/papers/modular-implicits.pdf" rel="nofollow noreferrer">modular implicits</a>, that allow one to combine the best of two worlds: maintaining the versatility and power of modules, while allowing hands-free coding by allowing one to pass modules implicitly. However, the implementation work has been stagnating for a few years, so I wouldn't expect them to be here soon.</p>

CC BY-SA 4.0
2024-10-25T09:13:23.550Z
2025-01-01T20:02:56.723Z
2025-01-01T20:02:56.723Z
xuq01
<p>In Rust, &quot;traits&quot; and &quot;types&quot; are entirely separate. You cannot write <code>struct Foo(SomeTrait)</code> or <code>fn bar(arg: SomeTrait)</code>[1]. A trait can be <em>converted</em> into a type in three ways:</p>
<ul>
<li>Bounded type parameter: <code>&lt;E: Trait&gt;</code>, then <code>E</code> is a type</li>
<li>Trait object: <code>dyn Trait</code></li>
<li><strong>Existential type:</strong> <code>impl Trait</code></li>
</ul>
<p>A <a href="https://doc.rust-lang.org/reference/items/traits.html" rel="nofollow noreferrer"><strong>trait</strong></a> consists of types, constants, and functions, which are called <a href="https://doc.rust-lang.org/reference/items/associated-items.html" rel="nofollow noreferrer">associated items</a>. Every type that <a href="https://doc.rust-lang.org/reference/items/implementations.html" rel="nofollow noreferrer"><em>implements</em></a> the trait does so by providing a definition for each associated item.[2] For example, a trait contains a function signature, and every type that implements the trait defines a function with the same signature and a different body.</p>
<p>An <a href="https://rust-lang.github.io/rfcs/2071-impl-trait-existential-types.html" rel="nofollow noreferrer"><strong>existential type</strong></a> is a type that implements a particular trait and is <a href="https://rust-lang.github.io/rfcs/2515-type_alias_impl_trait.html?highlight=existential#semantic-justification" rel="nofollow noreferrer"><em>opaque</em></a>. What this means is roughly, you can call the trait's methods and use its other associated items on the instance, and pass the instance to functions/constructors that take a generic or existential type that implements said trait or a supertrait (or functions/constructors that take the <em>exact</em> same existential), but nothing else.</p>
<pre class="lang-rust prettyprint-override"><code>// A trait
trait SomeTrait {
  // An associated function
  fn value(&amp;self) -&gt; u32;
}

// A type
struct Foo(&amp;'static str);
// Another type
struct Bar(u32);

// An implementation. This one makes it so `Foo` implements `SomeTrait`
impl SomeTrait for Foo {
  // Same signature as in `SomeTrait`: `fn value(&amp;self) -&gt; u32`
  fn value(&amp;self) -&gt; u32 {
    self.0.len() as u32
  }
}

// This implementation makes it so `Bar` implements `SomeTrait`
impl SomeTrait for Bar {
  // Same signature: `fn value(&amp;self) -&gt; u32`
  fn value(&amp;self) -&gt; u32 {
    // Different body
    self.0
  }
}

// This function returns an existential type.
fn helper() -&gt; impl SomeTrait {
  Foo(&quot;Hello&quot;)
}

fn main() {
  let foo = helper();
  // Even though at runtime, `foo` is guaranteed to be type `Foo`,
  // the type returned by `helper` is &quot;opaque&quot; in the sense that we
  // cannot use it like so. The following would be a compiler error:
  // &gt; println!(&quot;{}&quot;, foo.0);
  // We can only use it like any other type that implements `SomeTrait`;
  // this means we can only call `foo.value()`
  println!(&quot;{}&quot;, foo.value());  // Prints &quot;5&quot;
}
</code></pre>
<p>More formally, every existential type <code>O</code> that implements trait <code>T</code> has a corresponding <a href="https://rust-lang.github.io/rfcs/2515-type_alias_impl_trait.html?highlight=existential#semantic-justification" rel="nofollow noreferrer"><em>precise</em></a> type <code>P</code> (which may itself be existential, or is an implicit type parameter if the existantial type is in a parameter). There's a limited scope[3] in which you <code>P</code> and <code>O</code> can be used interchangeably, and instances of one can be assigned to places that expect the other. Outside of that scope, instances of <code>P</code> and <code>O</code> have no relation, and <code>O</code> can only be used as a type with a hidden structure that implements trait <code>T</code></p>
<hr />
<p>[1] You could write these <a href="https://doc.rust-lang.org/edition-guide/rust-2021/warnings-promoted-to-error.html#bare_trait_objects" rel="nofollow noreferrer">prior to Rust 2021</a>, but traits and types were still separate. <code>Trait</code> in type position was just syntax for a trait object (equivalent to today's <code>dyn Trait</code>), and this confusion is <a href="https://rust-lang.github.io/rfcs/2113-dyn-trait-syntax.html#the-current-syntax-is-often-ambiguous-and-confusing" rel="nofollow noreferrer">partly why it was deprecated and replaced by <code>dyn Trait</code></a>.</p>
<p>[2] Except associated items with default definitions. If a type doesn't provide an definition for one of those, it uses its default definition.</p>
<p>[3] The &quot;limited scope&quot; depends on the existential type's occurrence's location: whether the existential type is a parameter type, return type, <code>let</code>-binding type annotation, associated type definition, or type alias.</p>
<pre class="lang-rust prettyprint-override"><code>// Existential parameter: you can pass any type implementing `SomeTrait` to it,
// but inside the function body it's opaque.
fn foo(a: impl SomeTrait, i: usize) -&gt; u32 {
  if i == 0 {
    a.value()
  } else {
    3 + foo(a, i - 1)
  }
}

fn use_foo() {
  println!(&quot;{}&quot;, foo(Foo(&quot;Hello&quot;), 4));  // Prints &quot;17&quot;
  println!(&quot;{}&quot;, foo(Bar(5), 10));  // Prints &quot;35&quot;
}

// Existential return type: you can return any type implementing `SomeTrait`,
// but outside the function body it's opaque.
// Also, you cannot return different types in the same function
// (e.g. `if (i == 0) { Foo(&quot;Hello&quot;) } else { Bar(i) }` is illegal).
fn bar(i: u32) -&gt; impl SomeTrait {
  Bar(i * 10)
}

fn use_bar() {
  println!(&quot;{}&quot;, bar(10).value());  // Prints &quot;100&quot;
  println!(&quot;{}&quot;, foo(bar(20), 4));  // Prints &quot;212&quot;
}

fn baz() {
  // Existential `let`-binding type annotation: you can assign any type,
  // but the bound identifier is opaque.
  // Also, you cannot assign different types in the same `let` binding.
  // Requires `#![feature(impl_trait_in_bindings)]`, which as of Rust 1.82 is not implemented,
  // so the following actually won't compile:
  // &gt; let x: impl SomeTrait = Foo(&quot;Hello&quot;);
  // But we can get almost the same behavior with the following code,
  // which itself requires `#![feature(type_alias_impl_trait)]`
  type X = impl SomeTrait;
  let x: X = Foo(&quot;Hello&quot;);

  // The following is invalid:
  // &gt; println!(&quot;{}&quot;, x.0);
  // This is OK:
  println!(&quot;{}&quot;, x.value());  // Prints &quot;5&quot;
  // As is this:
  println!(&quot;{}&quot;, foo(x, 10));  // Prints &quot;35&quot;
}

struct Baz(u32);
impl Iterator for Baz {
  // Existential associated type: inside the `impl` block it's a precise type,
  // outside the `impl` block it's opaque.
  // It's also required in order to define an associated type to be an unnamed existential;
  // I cannot define `Item` to be anything else or `next` won't compile.
  // Requires `#![feature(impl_trait_in_assoc_type)]`
  type Item = impl SomeTrait;

  fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
    if self.0 == 0 {
      return None;
    }
    let i = self.0;
    self.0 -= 1;
    
    // Here's an example where existential types are required:
    // the type we return is an existential type.
    Some(bar(i))
  }

  // (Again, if there were other `Self::Item`s within the `impl` block,
  // they would all have to be the same type,
  // which in this case is a return value of a call to `bar`.)
}

mod qux {
  use super::*;

  // Existential type alias: inside the module it's a precise type,
  // outside the module it's opaque.
  // It's also required in order to use an unnamed existential in a named position without making it a generic;
  // I cannot define `T` to be anything else or `Ts` won't compile.
  // Requires `#![feature(type_alias_impl_trait)]`
  pub type T = impl SomeTrait;

  pub struct Ts {
    pub x: T,
    pub y: T
  }

  pub fn ts() -&gt; Ts {
    Ts {
      x: Baz(100).next().unwrap(),
      y: Baz(200).next().unwrap()
    }
  }
}

fn use_qux() {
  let ts = qux::ts();
  println!(&quot;{}&quot;, ts.x.value());  // &quot;1000&quot;
  println!(&quot;{}&quot;, ts.y.value());  // &quot;2000&quot;
}
<span class="math-container">```</span>
</code></pre>

CC BY-SA 4.0
2024-10-23T14:41:57.277Z
2024-10-23T14:41:57.277Z
tarzh
# How are existential types different from Rust's traits?
Posted by: username_0 on 2024-10-22
I am investigating ways to add some form of *abstract data types* to a toy language.

I was reading Graydon Hoare's [The Rust I Wanted Had No Future](https://graydon2.dreamwidth.org/307291.html), in which he talks about [existential types](https://en.wikipedia.org/wiki/Type_system#Existential_types). I have not used a language with existentials, but he seem to write about them as an alternative to traits, as a way to have *abstract data types*.

He writes this about traits:

> **Traits.** I generally don't like traits / typeclasses. To my eyes they're too type-directed, too global, too much like programming and debugging a distributed set of invisible inference rules, and produce too much coupling between libraries in terms of what is or isn't allowed to maintain coherence.

And about existentials:

> **Underpowered existentials.** The `dyn Trait` mechanism in Rust allows runtime and heterogeneous polymorphism, a.k.a. Existentials. These types are useful for many reasons: both solving heterogeneous representation cases and also selectively backing-off from monomorphization or inlining (when you have those) in order to favour code size / compile time or allow dynamic linking or runtime extension.

He also notes existentials in the section about *Missing Errors*:

> the `throws` syntax, the dedicated error-carrying ABI, and the not-necessarily-allocating existential Error type in Swift would have all helped to fill in this "explicit error union" model.

I get the impression that existentials are more like [Interfaces in Go](https://en.wikipedia.org/wiki/Go_(programming_language)#Interface_system) ─ that is, structural, as opposed to nominal. Traits in Rust are more powerful, and can contain default implementations for methods as well as act as *trait bounds* on generics.

How are existentials different from Rust's traits?
**Tags:** types rust traits interfaces existential-types
> **Comments:**
> **username_1**: If you have ever used a “dynamically-typed” language, you *have* used a language with existentials. A “dynamic type” is just $\sum_{T:\mathsf{type}} T$, which is an existential.  
---
## 3 answers
### Answer by username_6 on 2024-10-23. Score: 4 | Accepted answer
In Rust, "traits" and "types" are entirely separate. You cannot write struct Foo(SomeTrait) or fn bar(arg: SomeTrait)[1]. A trait can be converted into a type in three ways:

Bounded type parameter: , then E is a type
Trait object: dyn Trait
Existential type: impl Trait

A trait consists of types, constants, and functions, which are called associated items. Every type that implements the trait does so by providing a definition for each associated item.[2] For example, a trait contains a function signature, and every type that implements the trait defines a function with the same signature and a different body.
An existential type is a type that implements a particular trait and is opaque. What this means is roughly, you can call the trait's methods and use its other associated items on the instance, and pass the instance to functions/constructors that take a generic or existential type that implements said trait or a supertrait (or functions/constructors that take the exact same existential), but nothing else.
// A trait
trait SomeTrait {
  // An associated function
  fn value(&self) -> u32;
}

// A type
struct Foo(&'static str);
// Another type
struct Bar(u32);

// An implementation. This one makes it so `Foo` implements `SomeTrait`
impl SomeTrait for Foo {
  // Same signature as in `SomeTrait`: `fn value(&self) -> u32`
  fn value(&self) -> u32 {
    self.0.len() as u32
  }
}

// This implementation makes it so `Bar` implements `SomeTrait`
impl SomeTrait for Bar {
  // Same signature: `fn value(&self) -> u32`
  fn value(&self) -> u32 {
    // Different body
    self.0
  }
}

// This function returns an existential type.
fn helper() -> impl SomeTrait {
  Foo("Hello")
}

fn main() {
  let foo = helper();
  // Even though at runtime, `foo` is guaranteed to be type `Foo`,
  // the type returned by `helper` is "opaque" in the sense that we
  // cannot use it like so. The following would be a compiler error:
  // > println!("{}", foo.0);
  // We can only use it like any other type that implements `SomeTrait`;
  // this means we can only call `foo.value()`
  println!("{}", foo.value());  // Prints "5"
}

More formally, every existential type O that implements trait T has a corresponding precise type P (which may itself be existential, or is an implicit type parameter if the existantial type is in a parameter). There's a limited scope[3] in which you P and O can be used interchangeably, and instances of one can be assigned to places that expect the other. Outside of that scope, instances of P and O have no relation, and O can only be used as a type with a hidden structure that implements trait T

[1] You could write these prior to Rust 2021, but traits and types were still separate. Trait in type position was just syntax for a trait object (equivalent to today's dyn Trait), and this confusion is partly why it was deprecated and replaced by dyn Trait.
[2] Except associated items with default definitions. If a type doesn't provide an definition for one of those, it uses its default definition.
[3] The "limited scope" depends on the existential type's occurrence's location: whether the existential type is a parameter type, return type, let-binding type annotation, associated type definition, or type alias.
// Existential parameter: you can pass any type implementing `SomeTrait` to it,
// but inside the function body it's opaque.
fn foo(a: impl SomeTrait, i: usize) -> u32 {
  if i == 0 {
    a.value()
  } else {
    3 + foo(a, i - 1)
  }
}

fn use_foo() {
  println!("{}", foo(Foo("Hello"), 4));  // Prints "17"
  println!("{}", foo(Bar(5), 10));  // Prints "35"
}

// Existential return type: you can return any type implementing `SomeTrait`,
// but outside the function body it's opaque.
// Also, you cannot return different types in the same function
// (e.g. `if (i == 0) { Foo("Hello") } else { Bar(i) }` is illegal).
fn bar(i: u32) -> impl SomeTrait {
  Bar(i * 10)
}

fn use_bar() {
  println!("{}", bar(10).value());  // Prints "100"
  println!("{}", foo(bar(20), 4));  // Prints "212"
}

fn baz() {
  // Existential `let`-binding type annotation: you can assign any type,
  // but the bound identifier is opaque.
  // Also, you cannot assign different types in the same `let` binding.
  // Requires `#![feature(impl_trait_in_bindings)]`, which as of Rust 1.82 is not implemented,
  // so the following actually won't compile:
  // > let x: impl SomeTrait = Foo("Hello");
  // But we can get almost the same behavior with the following code,
  // which itself requires `#![feature(type_alias_impl_trait)]`
  type X = impl SomeTrait;
  let x: X = Foo("Hello");

  // The following is invalid:
  // > println!("{}", x.0);
  // This is OK:
  println!("{}", x.value());  // Prints "5"
  // As is this:
  println!("{}", foo(x, 10));  // Prints "35"
}

struct Baz(u32);
impl Iterator for Baz {
  // Existential associated type: inside the `impl` block it's a precise type,
  // outside the `impl` block it's opaque.
  // It's also required in order to define an associated type to be an unnamed existential;
  // I cannot define `Item` to be anything else or `next` won't compile.
  // Requires `#![feature(impl_trait_in_assoc_type)]`
  type Item = impl SomeTrait;

  fn next(&mut self) -> Option {
    if self.0 == 0 {
      return None;
    }
    let i = self.0;
    self.0 -= 1;
    
    // Here's an example where existential types are required:
    // the type we return is an existential type.
    Some(bar(i))
  }

  // (Again, if there were other `Self::Item`s within the `impl` block,
  // they would all have to be the same type,
  // which in this case is a return value of a call to `bar`.)
}

mod qux {
  use super::*;

  // Existential type alias: inside the module it's a precise type,
  // outside the module it's opaque.
  // It's also required in order to use an unnamed existential in a named position without making it a generic;
  // I cannot define `T` to be anything else or `Ts` won't compile.
  // Requires `#![feature(type_alias_impl_trait)]`
  pub type T = impl SomeTrait;

  pub struct Ts {
    pub x: T,
    pub y: T
  }

  pub fn ts() -> Ts {
    Ts {
      x: Baz(100).next().unwrap(),
      y: Baz(200).next().unwrap()
    }
  }
}

fn use_qux() {
  let ts = qux::ts();
  println!("{}", ts.x.value());  // "1000"
  println!("{}", ts.y.value());  // "2000"
}
```
---
### Answer by username_2 on 2024-10-23. Score: 6
You seem to have misunderstood the blog post. Existentials aren't an alternative to traits, and existentials aren't comparable with traits. It's a category error.
Rust does have existentials! dyn Trait "trait objects" and impl Trait "abstract types" are its notion of existential type. Compare GHC's ExistentialQuantification extension:
dyn Trait

forall a. Typeclass a => a

Hoare is merely complaining that dyn and impl are underpowered and underutilized/overly discouraged. This has nothing to do with his personal distaste for the trait system itself and for typeclass systems in general.
(A better Rust programmer than I may be able to elucidate his complaint about Rust's existentials in more detail--though I do notice that one lacking feature is the ability to existentially quantify generic type variables--but I believe this answers your question.)
> **Comments:**
> **username_3** (2024-10-23): Note that Rust's `impl Trait` syntax is sometimes also described as an "existential type," and it does have many seemingly arbitrary restrictions on where it may appear.  
> **username_4** (2024-10-23): @Kevin: Most restrictions on where `impl Trait` may appear are "temporary", there is a will to lift them, but it requires significant engineering effort, and thus will take time.  
---
### Answer by username_5 on 2024-10-25. Score: 2
You can encode traits as existentials, but I don't think this approach is helpful whatsoever
The canonical example for existential types are ML modules (note however that OCaml extensions to ML-type module systems extend it beyond existential types), and traits/type classes are somehow similar to ML modules, but with a few important differences.
Consider this ML (OCaml) code:
module type Ord =
  sig
    type 'a 
    val leq : 'a -> 'a -> bool
  end

This is an existential type: it could be written as $\exists \tau. \tau \rightarrow \tau \rightarrow \mathbf{2}$. $\tau$ is an abstract type
Now, there are two ways we could use this type:

given a function of type that can be written as $\alpha \to \alpha \to \mathbf{2}$ (where $\alpha$ is a type variable), i.e. fulfills the existential type, we may pack this value into a module such that it has existential type (i.e., $\alpha$ is now abstract and invisible)
given a value of this type (i.e., a module satisfying the signature Ord), we can unpack this value to use the value (in this case, the function $\leq$) abstracted within the module, without the programmer needing to know the implementation.

For example, if I'm writing a red-black tree, all I need to know is that the keys are comparable with each other. In the case of string, there may be many reasonable ways to compare them: e.g. in lexicographic order, by length, or otherwise. I don't need to know how it is implemented, yet I can still write code that is correct with regard to the implementation (and, in fact, all correct implementations).
A trait or type class is basically like a signature, except there could be only one instance (implementation). I can write something similar in Haskell:
class Ord a where
  (<=) :: a -> a -> Bool

It looks similar to a ML signature, right? But there could only be one instance of Ord a for each a! (There are some GHC extensions that allow one to violate this rule, but even if you have multiple, you don't get to choose which yourself, so this is generally considered bad practice.)
So it doesn't really have the same expressive power as ML modules and signatures. Existential types expand the expressive power of ML (i.e., allow previously unexpressible programs to be expressible), but type classes don't really. They can be thought of and implemented as a form of search and record passing: i.e., whenever you write <=, the compiler determines the type of the arguments (say T), search the type class database for an implementation of Ord for T (which is encoded as a record), and implicitly passes the record to your function. While it is more hands-off and automatic than modules and existentials, it does not provide the same level of expressive power that modules do. You won't be able to reasonably implement a counter, for example, using type classes.
So while it is possible to think of them as existentials, it is best not to, as it lacks the expressiveness of existentials.
Recently, there has been a line of work in OCaml, modular implicits, that allow one to combine the best of two worlds: maintaining the versatility and power of modules, while allowing hands-free coding by allowing one to pass modules implicitly. However, the implementation work has been stagnating for a few years, so I wouldn't expect them to be here soon.
---
