I want to pass a function that takes an arbitrary iterator over some type (e.g. String in the example below) into another function, but I don't know how to specify the type of such a function.
Here is a minimal (non-working) example of what I'm trying to achieve. The compiler cannot infer the type of I.
fn process<I>(lines: I)
where
I: Iterator<Item = String>, // or IntoIterator
{
for line in lines {
println!("{}", line.to_uppercase());
}
}
fn run<F, I>(processor: F)
where
I: Iterator<Item = String>,
F: Fn(I),
{
let v = vec![
String::from("aaa"),
String::from("BBB"),
String::from("cCcC"),
];
processor(v.iter());
}
fn main() {
run(process);
}
runisn't passing anyIterator<Item = String>it's currently passing a very specificstd::slice::Iter<'_, String>so you can't have a genericI: Iteratoron it. Anywaysslice::Iter<'_, String>implementsIterator<Item = &String>notIterator<Item = String>(note the additional/absent&) soprocessdoesn't even accept it.You probably meant to write this:
or this alternative
run: