Tim*_*ann 7 generics existential-type rust associated-types
I have an existential type defined like this:
trait Collection {
type Element;
}
impl<T> Collection for Vec<T> {
type Element = T;
}
type Existential<T> = impl Collection<Element = T>;
Run Code Online (Sandbox Code Playgroud)
A function, which takes a type implementing a trait with an associated type, returns this type. Why does this code work:
fn return_existential<I, T>(iter: I) -> Existential<T>
where
I: IntoIterator<Item = T>,
I::Item: Collection,
{
let item = iter.into_iter().next().unwrap();
vec![item]
}
Run Code Online (Sandbox Code Playgroud)
while this does not:
fn return_existential<I>(iter: I) -> Existential<I::Item>
where
I: IntoIterator,
I::Item: Collection,
{
let item = iter.into_iter().next().unwrap();
vec![item]
}
Run Code Online (Sandbox Code Playgroud)
trait Collection {
type Element;
}
impl<T> Collection for Vec<T> {
type Element = T;
}
type Existential<T> = impl Collection<Element = T>;
Run Code Online (Sandbox Code Playgroud)
When using a Vec directly, this works fine:
fn return_existential<I>(iter: I) -> Vec<I::Item>
where
I: IntoIterator,
I::Item: Collection,
{
let item = iter.into_iter().next().unwrap();
vec![item]
}
Run Code Online (Sandbox Code Playgroud)
Note: Those examples are constructed while playing around with this feature. I won't use it anyway as long as my IDE is not aware of existential types. Additionally, the exact syntax is subject to change.