Is this possible? `impl<V: Into<Vec<S>>, S: Into<String>> From<V> for Foo {..}`

I'm trying to implement the following:

struct Foo {
    x: Vec<String>,
}

impl<V: Into<Vec<S>>, S: Into<String>> From<V> for Foo {
    fn from(x: V) -> Self {
        Self { x: x.into() }
    }
}

(Playground)

But I get the following error message:

error[E0207]: the type parameter `S` is not constrained by the impl trait, self type, or predicates
 --> src/main.rs:5:23
  |
5 | impl<V: Into<Vec<S>>, S: Into<String>> From<V> for Foo {
  |                       ^ unconstrained type parameter

After reading E0207, it seems, this is not possible – is that correct?

If so: is there another way to archive this? I'm trying to avoid type parameters on Foo.

Basically, I'd like to be able to use Foo { x: ["bar"] }, etc.

Generics on an impl mean "duplicate this impl block for each possible choice of generic parameters", but if we define

struct MyType;
impl Into<Vec<&'static str>> for MyType {
    ...
}
impl Into<Vec<String>> for MyType {
    ...
}

then that duplication would result in implementing From<MyType> twice for Foo, which is not allowed.

Thanks, @alice!

then that duplication would result in implementing From<MyType> twice for Foo , which is not allowed.

Maybe I'm missing something, but why is this not possible? Vec, for example, has several From implementations, so why can't what I've tried result in a permutation of From implementations?

Because which one of this implementations should be used?

Because which one of this implementations should be used?

What I mean is, why can't the compiler generate a single implementation?

If I understand generics correctly, the following:

impl<S: Into<String>> From<S> for Foo { .. }

...would result in generated code like Foo::from_string, Foo::from_str, etc.

So I'm wondering why this:

impl<V: Into<Vec<S>>, S: Into<String>> From<V> for Foo { .. }

...can't result in Foo::from_vec_string, Foo::from_array_string, Foo::from_vec_str, Foo::from_array_str, etc.?

Wouldn't that be doable?

Because in Alice's example there would be two implementations for Foo::from_my_type.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.