Nested generic Option<V<T>>

Hello,

not sure if that is possible but maybe I'm wrong or there is a workaround for my task.

I have a function which takes vector of elements which can be converted into String.

fn select<T>(mut self, opt: Option<Vec<T>>) -> Self where T: Into<String>

What I want is ability to pass any collection which can be converted into iterator using into_iter() so I can pass into the function array for example.

Is that possible to have function like this?

fn select<V, T>(mut self, opt: Option<V<T>>) -> Self where V: IntoIterator, T: Into<String>

When I try to compile such code Rust says

src/odata/query_options.rs:26:46: 26:47 error: type parameters are not allowed on this type [E0109]
src/odata/query_options.rs:26     pub fn select<V, T>(mut self, opt: Option<V<T>>) -> Self where V: IntoIterator, T: Into<String> {
                                                                              ^

Thanks.

You can't use a generic parameter as a generic. That's what higher-kinded types are for, and Rust doesn't have them. Instead, you can just constrain the relevant associated type:

trait Something {
    fn select<Col>(mut self, opt: Option<Col>) -> Self
    where
        Col: IntoIterator,
        Col::Item: Into<String>;
}

Col::Item is shorthand for <Col as IntoIterator>::Item and is the element type for the iterator Col turns into.

2 Likes

Live and learn! That works! Thank you.