Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace impl trait return type with trait bound

Tags:

rust

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.

like image 280
Mohammed Essehemy Avatar asked Nov 01 '25 06:11

Mohammed Essehemy


1 Answers

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.

like image 87
BlackBeans Avatar answered Nov 03 '25 22:11

BlackBeans