How to create an unused iterator from a vector

Situation:

I have a situation where I would like to call some method defined by the attribute Iteratorfor the function parameter. The function I would like to name is to take a type parameter traitcalled VecLike. The function is called get_all_matching_rules.

get_all_matching_rulescan get either Vec, or another similar home type, which also implements Iterator. Of course, both of them implement VecLike. I was thinking of adding a function to VecLikeso that it returns Iteratorso that I can use it in get_all_matching_rules.

If my parameter is named: matching_rulesI could do matching_rules.iter().filter(.

Question:

How to return an unprofitable iterator from Vec?

I would like to return a non consuming iterator on Vec<T>type Iterator<T>. I do not want to iterate over elements while calling .iter().

If I have (where self is Vec):

fn iter<'a>(&'a self) -> Iterator<T> {
    self.iter()
}

I get the following error:

error: mismatched types: expected `core::iter::Iterator<T>+'a`, found `core::slice::Items<'_,T>` (expected trait core::iter::Iterator, found struct core::slice::Items)

I would like to return Iterator<T>. If there is a better way to go for it and not return it Iterator, I’m all ears.

+4
source share
2 answers

.iter() on [T], Vec<T> , , Iterator<&T>. , Iterator<&T>; Iterator - , , Items<T> - , Iterator<&T>. , , impl Iterator<&T>.

- Iterator<T>, Iterator<&T>. Rusts, , ; - , T &T. :

  • Copy, , . Iterator<&T>, T Copy, .map(|&x| x) .map(|x| *x) ( ).

  • Clone, , , Copy. Iterator<&T>, T Clone, .map(|x| x.clone()).

, v, v.iter().map(|x| x.clone()). , - :

fn iter<T: Clone>(slice: &[T]) -> Map<&T, T, Items<T>> {
    slice.iter().map(|x| x.clone())
}
+6

, .

.iter() (Items), Vec ( &T).

Filter ( ) . , chain() ?

, , Filter , .

0

All Articles