# Pre-RFC: returning automatically generating impl Trait

**URL:** <https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090>\
**Category:** language design\
**Created:** [September 17, 2020, 6:28pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090 "2020-09-17T18:28:52Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [September 17, 2020, 6:28pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/1 "2020-09-17T18:28:53Z")

</div>

If you like to use iterator, you will at one point try to write the following code:

```rust
fn create_iterator() -> impl Iterator<Item=Foo> { /* ... */ }
fn generate_iterator() -> impl Iterator<Item=Foo> { /* ... */ }

```

```rust
fn create_or_generate(condition: bool) -> impl Iterator<Iter=Foo> {
    if condition {
        create_iterator()
    } else {
        generate_iterator()
    }
}

```

The intent of the code is perfectly clear by unfortunately the compiler will reject it:

```rust
error[E0308]: `if` and `else` have incompatible types
  --> src/lib.rs:9:9
   |
3 | fn generate_iterator() -> impl Iterator<Item=Foo> { ... }
   | ----------------------- the found opaque type
...
6 | / if condition {
7 | | create_iterator()
   | | ----------------- expected because of this
8 | | } else {
9 | | generate_iterator()
   | | ^^^^^^^^^^^^^^^^^^^ expected opaque type, found a different opaque type
10 | | }
   | | _____ - `if` and `else` have incompatible types
   |
   = note: expected type `impl std::iter::Iterator` (opaque type at <src/lib.rs:2:25>)
           found opaque type `impl std::iter::Iterator` (opaque type at <src/lib.rs:3:27>)
   = note: distinct uses of `impl Trait` result in different opaque types

```

A solution would be to slightly modify the code like this:

```rust
fn create_or_generate(condition: bool) -> impl Iterator<Item=Foo> {
    if condition {
        Iter::T1(create_iterator())
    } else {
        Iter::T2(generate_iterator())
    }
}

enum Iter<T1, T2> {
    T1(T1),
    T2(T2),
}

impl<T1, T2> Iterator for Iter<T1, T2>
where
    T1: Iterator<Item=Foo>,
    T2: Iterator<Item=Foo>,
{
    type Item=Foo;
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Iter::T1(t1) => t1.next(),
            Iter::T2(t2) => t2.next(),
        }
    }
}

```

This code is very verbose, and desn't add value for the reader.

* * *

Instead, I would propose make the initial snipped valid Rust. The compiler would (if needed) auto-generate an union that implements `SomeTrait` when a function returns `impl SomeTrait` and there are two or more types implementing `SomeTrait` returned by the function.

In term of design, I think that no markers (like the `Iter::T1(...)` that I used in the example above, a potential `.into()`, or a new keyword) are needed when converting from one concrete type into the compiler-generated union. Indeed, it's obvious that a conversion is needed (otherwise the could would not compile), and both the source and destination of the conversion are known and ambiguous. Implicit conversion is already a mechanism that exists in Rust (with the `?` operator), and I think we can have them here since they can't introduce ambiguities.

* * *

Before formalizing this idea in a proper RFC, I wanted to gather feedback. I am also willing (if this idea is accepted) to implement it, but I will probably need some mentoring.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [September 17, 2020, 7:04pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/2 "2020-09-17T19:04:14Z")

</div>

This has come up before, often called "enum impl trait". Searching for that will find a bunch of threads, such as [Extending `impl Trait` to allow multiple return types](https://internals.rust-lang.org/t/extending-impl-trait-to-allow-multiple-return-types/7921)

> [@robinm](#):
>
> I think that no markers are needed

I think this will be the biggest conceptual sticking point (as opposed to implementation-detail difficulties). Many will argue that they would like this to be opt-in, I suspect. (One possible argument: This adds a branch to every use of the returned value, which is something that shouldn't be added invisibly.)

One hard question that might force it to have an opt-in marker of some sort: how would it pick between doing the compiler-generated enum and doing a coercion, if one is available?

---

<div class="post-metadata">

**Author:** ![tspiteri](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tspiteri/32/7283_2.png) [@tspiteri](https://internals.rust-lang.org/u/tspiteri)\
**Post date:** [September 17, 2020, 8:16pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/3 "2020-09-17T20:16:52Z")

</div>

The error is in the `if` expression, not in the function that returns impl trait. So what you are suggesting seems to me to be modification of `if` expressions, unless you plan to use something like

```rust
if condition {
    return create_iterator();
} else {
    return generate_iterator();
}

```

---

<div class="post-metadata">

**Author:** ![joeschman](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/joeschman/32/2862_2.png) [@joeschman](https://internals.rust-lang.org/u/joeschman)\
**Post date:** [September 17, 2020, 8:36pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/4 "2020-09-17T20:36:36Z")

</div>

I always thought that `enum impl trait` would be a nice feature to have, but didn't ever think deeply about how it should work. I'm not sure if this issue has already come up, but I think the automatic trait generation gets in trouble with binary operations, in the same way as subtyping would. Consider the following:

```rust
trait Magma {
    fn op(self, other: Self) -> Self;
}

impl Magma for usize {
    fn op(self, other: Self) -> Self {
        self + other
    }
}

impl Magma for String {
    fn op(self, other: Self) -> Self {
        format!("{}{}", self, other)
    }
}

fn get_magma(condition: bool) -> impl Magma {
    if condition {
        String::from("bla")
    } else {
        3
    }
}

fn main() {
    let m1 = get_magma(true);
    let m2 = get_magma(false);
    // what should happen here?
    let result = m1.add(m2);
}

```

---

<div class="post-metadata">

**Author:** ![bill\_myers](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bill_myers/32/4085_2.png) [@bill\_myers](https://internals.rust-lang.org/u/bill_myers)\
**Post date:** [September 17, 2020, 9:58pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/5 "2020-09-17T21:58:07Z")

</div>

Could use syntax like this to be fully explicit:

```rust
type R = enum impl Iterator<Iter=Foo>;
fn create_or_generate(condition: bool) -> R{
    if condition {
        create_iterator() as R
    } else {
        generate_iterator() as R
    }
}

```

Or this syntax might be enough:

```rust
fn create_or_generate(condition: bool) -> enum impl Iterator<Iter=Foo> {
    if condition {
        create_iterator()
    } else {
        generate_iterator()
    }
}

```

Removing the enum specification completely seems problematic since it would allow to introduce silent overhead, and also it only works for a subset of traits including the object-safe ones as pointed out by @joeschman .

---

<div class="post-metadata">

**Author:** ![taiki-e](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/taiki-e/32/5017_2.png) [@taiki-e](https://internals.rust-lang.org/u/taiki-e)\
**Post date:** [September 17, 2020, 10:11pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/6 "2020-09-17T22:11:29Z")

</div>

See also [https://github.com/rust-lang/rfcs/issues/2414](https://github.com/rust-lang/rfcs/issues/2414). (Its thread is long, but as far as I know, there is the most specific discussion on this topic.)

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [September 17, 2020, 10:16pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/7 "2020-09-17T22:16:16Z")

</div>

Another option would be something more internal to the method, sketch

```rust
fn create_or_generate(condition: bool) -> impl Iterator<Iter=Foo> {
    enum match condition {
        true => create_iterator(),
        false => generate_iterator(),
    }
}

```

Because the fact that it's becoming an enum is local to the particular branching expression -- once the value of that type exists, it doesn't need anything special at the signature level. And this way you could make a local variable of such a type too.

(Plenty of gaps in that sketch too, like doing it with early return, what it would look like in nested-ifs, etc.)

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [September 17, 2020, 10:58pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/8 "2020-09-17T22:58:37Z")

</div>

I should have said explicitely that I'm aware of the previous discussion about enum impl trait. At one point it appeared that enum impl trait where filling two needs:

- **creating an opaque type from two or more (possibly opaque) types all implementing the same trait** (this proposal). This is especially useful to create iterators from iterators of different types
- **creating an anonymous closed set of known type** (a bit like C++ variant). This is especially useful for error handling when one want to specify exactly the possible error types, and not use a catch-all enum for the whole crate. This proposition is **not** about that part.

* * *

> [@scottmcm](#):
>
> I think this will be the biggest conceptual sticking point (as opposed to implementation-detail difficulties). Many will argue that they would like this to be opt-in, I suspect. (One possible argument: This adds a branch to every use of the returned value, which is something that shouldn't be added invisibly.)

This is a very valid question. I would argue that a marker is not needed, because :

- if this proposition is rejected the code would not compile anyway.
- it's already explicit that some overhead can be added because of the **`impl Trait`** in the return type of the function
- there is no way to write a better version by hand than what the compiler could generate

So I think that _adding_ syntax should be motivated, not the reverse.

* * *

> [@joeschman](#):
>
> ```rust
> trait Magma {
> fn op(self, other: Self) -> Self;
> }
> 
> impl Magma for usize { /*…*/ }
> impl Magma for String { /* … */ }
> 
> fn get_magma(condition: bool) -> impl Magma { /* ... */ }
> 
> fn main() {
> let m1 = get_magma(true);
> let m2 = get_magma(false);
> // what should happen here?
> let result = m1.add(m2);
> }
> 
> ```

With or without this proposal, the code cannot compile because `Add<T: Magma>` is not implemented for `Magma`.

This proposal would only automatically generate the boilerplate in `get_magma()` needed to make this very function compiles. Rust semantic is not changed, and there is no way to see from the outside how `get_magma()` is implemented.

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [September 17, 2020, 11:42pm UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/9 "2020-09-17T23:42:50Z")

</div>

> [@tspiteri](#):
>
> The error is in the `if` expression, not in the function that returns impl trait. So what you are suggesting seems to me to be modification of `if` expressions, unless you plan to use something like

I didn't realized that my proposition could be both extended and the rule simplified at the same time. Thanks for pointing my attention on this specific detail.

Currently there are multiple construction that requires to unify types: if, if let, loop with multiple break values and functions (I don't think I forgot one, please correct me if I'm wrong). Currently, to be unified, all the branches must have the same (possibly opaque) type. With this proposition, all constructions that have multiple branch would create a value whose type is:

- the common type of all branches (this is what is done currently)
- an opaque type that implements all traits implemented by all the branches

EDIT: this rule is too permissive and would lead to bad error messages. I re-wrote those example in a later post. The trait implemented by the opaque type should be made explicit.

Let's try with some examples:

```rust
trait Trait {}
fn foo() -> f32;
fn bar() -> f32;
fn baz() -> impl Trait;
impl Trait for f32 {}

let value: if condition {
    foo()
} else {
    bar()
}; // shared types for all branches, unifies as f32

let value: if condition {
    foo()
} else {
    baz()
}; // no shared type, but a shared trait for all branches, unifies as Trait

trait Other {}
fn other() -> impl Other;

let value: if condition {
    baz()
} else {
    other()
}; // no shared type, and no common trait, no unification possible, doesn't compiles

```

* * *

If also forgot to talk about `Sized` and `unsafe` traits.

- The unification is trivial to do using the mechanism presented in the first post for `Sized` types, but (at least I don't see how to do it) it seems not possible to do it for `!Sized` types. This initial version would only extend the current rules for `Sized` types, and would not try to unify `!Sized` types (resulting in a compile error).
- In previous discussion around `enum impl Trait`, some concern where raised about automatically implementing unsafe trait (it's not sound). This means that this proposition should obviously exclude unsafe trait (unless put inside an unsafe block). However, I don't saw any issue raised against automatically implementing Safe traits.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [September 18, 2020, 12:16am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/10 "2020-09-18T00:16:58Z")

</div>

> [@robinm](#):
>
> it's already explicit that some overhead can be added because of the **`impl Trait`** in the return type of the function

While that would be true with this proposal, _today_ using `impl Trait` is no slower than returning the concrete type, and that's one of its advantages -- using it lets you tweak your semver promises without changing the concrete code that executes.

Of course the version of this that already works today is `Box::new(x) as Box<dyn Trait>`, which adds extra overhead and is explicit about doing it.

That does make me think that another way to do this would be some sort of bounded-size `dyn Trait` holder -- if it's only going to work for dyn-capable traits anyway, does it really need to go through enum dispatch instead of just using a fat pointer and dispatching that way? Another way to phrase this is "less general `Box<dyn Trait>` so I don't have to pay for allocation".

---

<div class="post-metadata">

**Author:** ![josh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/josh/32/5934_2.png) [@josh](https://internals.rust-lang.org/u/josh)\
**Post date:** [September 18, 2020, 6:19am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/11 "2020-09-18T06:19:00Z")

</div>

> [@robinm](#):
>
> I would argue that a marker is not needed, because :
> 
> - if this proposition is rejected the code would not compile anyway.

"This feature is okay because without it the code wouldn't have compiled" is not a universal argument. Sometimes you don't _want_ the code to compile. The compiler's job is often to tell you that your code doesn't compile, rather than trying to find some meaning that allows compiling your code.

---

<div class="post-metadata">

**Author:** ![joeschman](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/joeschman/32/2862_2.png) [@joeschman](https://internals.rust-lang.org/u/joeschman)\
**Post date:** [September 18, 2020, 6:22am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/12 "2020-09-18T06:22:18Z")

</div>

Sorry my bad. In the last line i meant to call `op`, and not `add`. The corrected example:

```rust
trait Magma {
    fn op(self, other: Self) -> Self;
}

impl Magma for usize { /*…*/ }
impl Magma for String { /* … */ }

fn get_magma(condition: bool) -> impl Magma { 
  If condition {
    Strring::from("bla")
  } else {
    3
  }
}

fn main() {
    let m1 = get_magma(true);
    let m2 = get_magma(false);
    // what should happen here?
    let result = m1.op(m2);
}

```

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [September 18, 2020, 6:39am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/13 "2020-09-18T06:39:19Z")

</div>

This is a bad idea in general because it allows arbitrarily unifying types in any branch expression as long as they have some trait in common. Given that almost all types implement e.g. `Debug` (or to say something even more drastic, think `Sync` or `Send`), this would effectively lead to dynamic typing.

---

<div class="post-metadata">

**Author:** ![joeschman](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/joeschman/32/2862_2.png) [@joeschman](https://internals.rust-lang.org/u/joeschman)\
**Post date:** [September 18, 2020, 6:43am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/14 "2020-09-18T06:43:54Z")

</div>

Fair point. I see horrible error messages from the compiler coming.

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [September 18, 2020, 7:03am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/15 "2020-09-18T07:03:44Z")

</div>

> [@scottmcm](#):
>
> Of course the version of this that already works today is `Box::new(x) as Box<dyn Trait>` , which adds extra overhead and is explicit about doing it.

There is a second possibility (in current Rust) that also return an `impl Trait`. The one that I used in the first post.

> [@scottmcm](#):
>
> That does make me think that another way to do this would be some sort of bounded-size `dyn Trait` holder -- if it's only going to work for dyn-capable traits anyway, does it really need to go through enum dispatch instead of just using a fat pointer and dispatching that way? Another way to phrase this is "less general `Box<dyn Trait>` so I don't have to pay for allocation".

There are effectively two possibilities for this issue:

- a "fat" `impl Trait`: wrapping all values in an enum (union + discriminant): this proposal, dispatching using the discriminant
- a "fat" `dyn Trait`: wapping all values in an union + vtable pointer, dispatching using the vtable

That's interesting and need to be explored further, but I personally think that the former is more interesting. I don't think that both should exists, they seems to fill the same need.

> [@josh](#):
>
> "This feature is okay because without it the code wouldn't have compiled"

Definitively! However, I wanted (but fail to emphasis) that ”it's ok to not add syntax“ because all the 3 points _at the same_ time are true.

> [@joeschman](#):
>
> Sorry my bad. In the last line i meant to call `op` , and not `add` . The corrected example:

It's exactly the same issue. With or without this proposal this code doesn't compile because you didn't provide:

```rust
impl <T: Magma> Magma for T { /* … */ }

```

This proposal only generates boilerplate **inside** a function and doesn't change anything on how the function can be manipulated from the outside. Since this function returns an opaque `impl Magma`, you can only use construction that accept `T: Magma`.

> [@H2CO3](#):
>
> This is a bad idea in general because it allows arbitrarily unifying types in any branch expression as long as they have some trait in common.

> [@joeschman](#):
>
> Fair point. I see horrible error messages from the compiler coming.

In the initial post, this was not an issue, because the only place where the unification could occur was in an expression that directly returns. The type of this expression was already constraint by the return type of the function (`impl SomeTrait`). However since I later extended this idea to any expression that have multiples incompatible types, this could definitively lead to horrible error message. I think that it's relatively easy to fix: an expression can be promoted to an opaque `impl Trait` if and only if the type of that expression is explicit:

```rust
trait Trait {}
fn foo() -> f32;
fn bar() -> f32;
fn baz() -> impl Trait;
impl Trait for f32 {}

let value: impl Trait = if condition {
    foo()
} else {
    bar()
}; // shared types for all branches, unifies as f32, but can only be manipulated as an opaque type

let value: impl Trait = if condition {
    foo()
} else {
    baz()
}; // no shared type, but an explicit shared trait for all branches, unifies as Trait (using an enum as proposed)

let value = if condition {
    foo()
} else {
    baz()
}; // will not compiles since the compiler doesn't have the right to do unification unless the unified type is explicit

fn abc() -> Trait {
    if condition {
        foo()
    } else {
        baz()
    }
} // no shared type, but an explicit shared trait for all branches, unifies as Trait (using an enum as proposed)

trait Other {}
fn other() -> impl Other;

let value: impl ??? = if condition {
    baz()
} else {
    other()
}; // no shared type, and no common trait, no unification possible, doesn't compiles

```

---

<div class="post-metadata">

**Author:** ![withoutboats](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/withoutboats/32/4560_2.png) [@withoutboats](https://internals.rust-lang.org/u/withoutboats)\
**Post date:** [September 18, 2020, 8:21am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/16 "2020-09-18T08:21:28Z")

</div>

This is an example of the weakness of `type Foo = impl Trait;` as the syntax for named existentials. This could be a feature of the `-> impl Trait` syntax, but not a feature of `abstract type Foo: Trait;` syntax, so that users who want to guarantee its a single type can use that syntax. But it feels much more arbitrary to restrict it when they both use impl trait syntax.

This split feels right though: my feeling is that unifying all branches when the return type is anonymous is usually desirable, whereas unifying all branches when you've named an existential is usually not.

---

<div class="post-metadata">

**Author:** ![joeschman](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/joeschman/32/2862_2.png) [@joeschman](https://internals.rust-lang.org/u/joeschman)\
**Post date:** [September 18, 2020, 8:42am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/17 "2020-09-18T08:42:37Z")

</div>

My point is that without the proposal it does compile. Check out this playground: [https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f3ed2aace4889dbeff49fb642f6b8a81](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f3ed2aace4889dbeff49fb642f6b8a81) Why should I provide `impl <T: Magma> Magma for T { /* … */ }`? You want to reimplement `Magma` for types that implement `Magma` ?

I am aware that you only want to generate boilerplate within the function. But the question is how you would generate the boilerplate for this trait? I reckon that's not possible at all. Therefore we'd need some rules for enum-safe traits. I think these rules would need to be almost the same as the ones for object-safe traits. Except that they could allow for associated types, as long as the associated types of all the types that should be wrapped in an enum are the same.

Also I think since enum impl trait is not possible for every trait, I think it should definitely have a keyword in order to prevent people from relying on enum impl trait without being aware that this is not possible for every trait.

---

<div class="post-metadata">

**Author:** ![joeschman](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/joeschman/32/2862_2.png) [@joeschman](https://internals.rust-lang.org/u/joeschman)\
**Post date:** [September 18, 2020, 8:44am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/18 "2020-09-18T08:44:03Z")

</div>

> [@robinm](#):
>
> `fn baz() -> impl Foo;`

You did mean `fn baz() -> impl Trait;` here, right?

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [September 18, 2020, 9:02am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/19 "2020-09-18T09:02:34Z")

</div>

> [@withoutboats](#):
>
> This is an example of the weakness of `type Foo = impl Trait;` as the syntax for named existentials

I hope that I understand correctly your point. Please correct me if I'm wrong. `let val: impl Trait = expression` can mean two things:

- “Dear compiler, could you please check that `expr` returns a type that implements the trait `Trait`, the hide the concrete type, but don't modify it in any way”
- “Dear compiler, could you please create an opaque type that implements the trait `Trait` by unifying all the branches of `expr`, and if needed add whatever is needed to make it compile” (this proposal)

Since the former proposition is definitively a valid need, then the later would need some syntax to differentiate itself from the former.

> [@joeschman](#):
>
> My point is that without the proposal it does compile.

My bad. My mental compiler had probably an ICE! That's effectively right. This means that such coercion could only work for trait that don't take `Self` (or any variation with references and pointers) in the arguments of any functions (except for `self` itself obviously). I need to think about it, since it feels that it's a major limitation.

* * *

> [@joeschman](#):
>
> You did mean `fn baz() -> impl Trait;` here, right?

Thanks, fixed

* * *

Btw, thanks all. I got exactly the kind of feedback that I was hoping for!

---

<div class="post-metadata">

**Author:** ![dhm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/dhm/32/4879_2.png) [@dhm](https://internals.rust-lang.org/u/dhm)\
**Post date:** [September 18, 2020, 11:08am UTC](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090/20 "2020-09-18T11:08:41Z")

</div>

Note that with continuation-passing style, especially [after sugaring](https://docs.rs/with_locals), we get to write:

```rust
#[with]
fn create_or_generate (condition: bool)
  -> &'self mut (dyn Iterator<Item = Foo>)
{
    if condition {
        &mut create_iterator()
    } else {
        &mut generate_iterator()
    }
}

```

Doing so, besides the CPS constraints, replaces an `enum` / discriminant-based dynamic dispatch with a virtual method one.

But it has the advantage of not being magic: we are using the classic `&mut impl Iterator<...> as &mut dyn Iterator<...>` vtable-based type erasure coercion.

- For those skeptical of that `#[with]` and `'self` stuff from CPS, know that that is just a library-based way of implementing the `unsized_locals` feature, whereby we would have been able to otherwise write:

* * *

In that regard, it becomes now more intuitive / obvious that we should have a way to express the coercion from an `impl Iterator` to an `enum dyn Iterator` type, making it thus relate back to the linked / mentioned "anonymous / auto- `enum`" proposals.

It also makes the following suggested idea especially resonate:

> [@scottmcm](#):
>
> Another option would be something more internal to the method, sketch
> 
> ```rust
> fn create_or_generate(condition: bool) -> impl Iterator<Iter=Foo> {
> enum match condition {
> true => create_iterator(),
> false => generate_iterator(),
> }
> }
> 
> ```

- I initially wasn't that fond of the `enum` as a (contextual) keyword modifier for expressions, and started suggesting a coercion syntax (explicit, such as `as enum dyn ...`, or implicit, such as with type ascription or a typed binding).

* * *

There is one thing remaining though, which is:

### How to enable `enum dyn`-dispatch for arbitrary traits

It definitely should not be automatic, since traits can express arbitrary properties, not just method-based APIs. For instance, let's imagine layout-related marker traits, such as [`ReprC`](https://docs.rs/safer-ffi/0.0.5/safer_ffi/layout/trait.ReprC.html), [`FromBytes`](https://docs.rs/zerocopy/0.3.0/zerocopy/trait.FromBytes.html), [`Layout`](https://docs.rs/typic/0.3.0/typic/layout/trait.Layout.html). These should definitely not carry through.

Also for retro-compatibility reasons (in this case, adding unexpected implementors of some traits can cause logic bugs or even unsoundness (_c.f._, these layout-based `unsafe` traits). So it needs to be something `opt-in`, for _each_ and every trait.

Having a special trait attribute then seems to be the most straightforward approach:

```rust
#[bikeshed_name]
trait Iterator { ... }
// e.g.
#[auto_enum]
trait Iterator { ... }

```

* * *

Another approach, but which would require variadic generics, or genericity over traits, would be to have `enum match ...` expression not have a fully anonymous type, but only an anonymous type parameter within some known wrapper type:

- 
#### Variadic generics (+ magical `AutoEnum` def)

```rust
#[lang(auto_enums)]
enum AutoEnum<Ts...> { Ts... } // super fictional syntax

```

And then people would opt-in using:

```rust
impl<Item, Ts... : Iterator<Item = Item>> Iterator
    for AutoEnum<Ts...>
{
    type Item = Item;

    /* built-in impl for _methods_ ? */
}

```

- 
#### Genericy over traits

```rust
#[lang(auto_ennums)]
struct AutoEnum<trait Trait, __> { ... } //__ represents the unnameable auto-generated type

impl<Item, __> Iterator
    for AutoEnum<trait Iterator<Item = Item>, __>
{
    type Item = Item;
    /* auto-generated for methods */
}

```

  - Note that for this use case, genericity over traits can be hacked / emulated using a `?Sized` type parameter that would be using `dyn Trait` afterwards. Despite the appealing simplicity of so doing, so doing would be intermixing different notions (for instance, an `enum dyn Trait` could have methods taking `self` by value, whereas a classic `dyn Trait` cannot (unless `unsized_locals` were available)).

Note that the `AutoEnum` wrapper type has the advantage of no longer truly requiring the `enum match`, by making it possible to go back to my initial idea of a type coercion:

- 

```rust
match condition {
    | true => create_iterator(),
    | false => generate_iterator(),
} as AutoEnum<impl Iterator, impl Iterator>

```

- 

```rust
match condition {
    | true => create_iterator(),
    | false => generate_iterator(),
} as AutoEnum<trait Iterator, _>

```

* * *

All in all, I find the whole implementation far from trivial, and wonder if `#[with] ... StackBox<'self, dyn Iterator>` / `unsized_locals` or manually written _ad-hoc_ `Either`-like `enum`s don't suffice to solve real use-case needs 🤔

[Next page](https://internals.rust-lang.org/t/pre-rfc-returning-automatically-generating-impl-trait/13090.md?page=2)
