Can this be expressed in stable Rust, or do I need GAT?

trait MyTrait;

struct A;
struct B;
struct C;

struct Generic<T: MyTrait>;

struct Other;

impl Into<Other> for Generic<A> { /* ... */ }
impl Into<Other> for Generic<B> { /* ... */ }
impl Into<Other> for Generic<C> { /* ... */ }

I would like to create such function:


fn generic_foo<T: MyTrait>(g: Generic<T>) -> Other {
    g.into()
}

Of course it doesn't work since Generic<T: MyTrait> doesn't implements Into<Other> (even if for all types T that implement MyTrait, Generic<T> implements Into<Other>). Is there a way to write such function generic_foo() on stable Rust, or does this requires GAT?

How about this?

fn generic_foo<T: MyTrait>(g: Generic<T>) -> Other 
where
    Generic<T>: Into<Other>
{
    g.into()
}

Note that you should prefer implementing From rather than Into.

2 Likes

Perfect! Thanks Alice.

I implemented From in my code, but forgot to do the same here :wink: Good advice, though!