dspyz
dspyz

Reputation: 5514

Generalize over iterators over references and iterators over values

I want to implement a trait for which one of the functions takes an iterator as an argument and then operates on the values returned by that iterator as immutable references.

However I would also like my function to work on iterators over values as well (without having to duplicate code). How can I do that?

The following does not work:

impl<T, I: Iterator> FilterItem for SortedFilter<I> where  T: Ord, I::Item: Borrow<T> {
    ...
}

I get

error: the type parameter `T` is not constrained by the impl trait, self type, or predicates

Upvotes: 0

Views: 70

Answers (1)

Shepmaster
Shepmaster

Reputation: 431689

You are looking for the Borrow trait:

When writing generic code, it is often desirable to abstract over all ways of borrowing data from a given type

use std::borrow::Borrow;

fn print_it<I, T>(iter: I)
    where I: Iterator<Item = T>,
          T: Borrow<u8>
{
    for v in iter {
        let a: &u8 = v.borrow();
        println!("{}", a);
    }
}


fn main() {
    let vals = vec![1,2,3];
    print_it(vals.iter()); // Iterator of references
    print_it(vals.into_iter()); // Iterator of values
}

Upvotes: 2

Related Questions