Is it possible to change this impl trait return type to a trait bound?
fn combine_vecs<T: Copy>(v: Vec<T>, u: Vec<T>) -> impl Iterator<Item=T> {
v.into_iter().chain(u.into_iter()).cycle()
}
I tried something like this
fn combine_vecs<T: Copy, TI: Iterator<Item=T>>(v: Vec<T>, u: Vec<T>) -> TI {
v.into_iter().chain(u.into_iter()).cycle()
}
but it fails with the following error
expected type parameter `TI`
found struct `Cycle<std::iter::Chain<std::vec::IntoIter<T>, std::vec::IntoIter<T>>>`
Not sure why it fails although the struct implements the required trait.
No, you can't in this specific situation. impl Trait does not always have the same meaning.
If it's in the return position of a function declaration, it means "there is a type that implements this trait that is returned by this function". If, instead, you put a generic type TI: Trait and returned it, it means "for any type TI provided by the caller that implements Trait, I can provide a function that returns TI".
It's quite clear that in your example, you want the first solution, because the return type of your function is Cycle<Chain<IntoIter<T>, IntoIter<T>>>. So the only way to replace the impl Iterator<Item=T> would be to specify the concrete type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With