Confusion with implementing trait and unconstrained types

So I have the following trait:

pub trait Empty {
    fn empty() -> Self
}

and I want the following impl:

impl<A, T: FromIterator<A>> Empty for T {
    fn empty() -> Self {
        [].iter().collect()
    }
}

but I get the error that A is unconstrained. Worse yet, I can't get rid of A since FromIterator needs it. Also, FromIterator is a trait, so I can't just impl<A> Empty for FromIterator<A>.

How do I get such an implementation?

It's an error because T could implement FromIterator for multiple different As, and the compiler has no way to choose which one to use in your implementation. You could parameterize your trait though, Empty<A>.

Also, [].iter() will produce references, slice::Iter<A> with Item = &A. You could add .cloned() or .copied() with the added constraint on A. Better yet, use an Option like None.into_iter(), or the built-in std::iter::empty().

1 Like