Given a Range
, is there a good way to iterate over the reference of the items rather than items themselves? I'd like to write a function that takes an iterator to a structure that contains a number of unsigned integers. Most of the time, the structure will be either a vector or a range. In the case of a vector, the iterator gives a reference to the elements, which is the desired behavior. In the case of a range, we get the integers themselves, which doesn't type check. For example, consider the code:
// Take in an iterator and print it
fn foo<'a, T>(t: T)
where
T: Iterator<Item = &'a usize>,
{
for u in t {
println!("{}", *u)
}
}
// Run the function
fn main() {
let x = vec![1, 3, 8];
foo(x.iter());
foo(x.iter());
foo((1..4).collect::<Vec<usize>>().iter());
//foo(1..4);
}
This code works fine and gives:
1
3
8
1
3
8
1
2
3
Note, it's important to our situation that foo
does not consume x
. That said, the syntax for the range is cumbersome. If we uncomment the above line, we get:
error[E0271]: type mismatch resolving `<std::ops::Range<{integer}> as Iterator>::Item == &usize`
--> src/main.rs:20:5
|
5 | fn foo<'a, T>(t: T)
| --- required by a bound in this
6 | where
7 | T: Iterator<Item = &'a usize>,
| ---------------- required by this bound in `foo`
...
20 | foo(1..4);
| ^^^ expected `&usize`, found integer
This makes sense. The range converts to an iterator with the wrong type. I'd like to fix that, or the routine, so that we can type either foo(x.iter())
or foo(1..4)
and not have to clone x
. Can this be accomplished?