I would like to write a function from Iterator<Item=A>
to Iterator<Item=B>
. For example:
fn test_iterator<I,O>(input: I) -> O
where I: Iterator<Item=i32>,
O: Iterator<Item=String> {
input.map(|x| x.to_string());
}
I get the compiler error:
expected type parameter, found struct std::iter::Map
Next try was to give it this more specific type:
fn test_iterator<I,F>(input: I) -> Map<I,F>
where I: Iterator<Item=i32>,
F: FnMut(i32) -> String {
input.map(|x| x.to_string())
}
This gives me the error:
expected type parameter, found closure
= note: expected type F
found type [closure@parser.rs:14:15: 14:32]
Is there a possibility to annotate the return type of the function?
I don't want to go to something like Vec, because I would like to have composable functions on Iterators, e.i. I don't want:
fn test_iterator<I>(input: I) -> Vec<String>
where I: Iterator<Item=i32> {
input.map(|x| x.to_string()).collect()
}
I think it boils down to the same question how to explicitly annotate the type of r1
and r2
in the following example:
fn test_iterator2<I>(input: I) -> Vec<String>
where I: Iterator<Item=i32> {
let r1 = input.map(|x| x.to_string());
let r2 = r1.map(|s| s.to_uppercase());
r2.collect()
}
Am I missing something or is this kind of generic programming not possible in Rust?
Regards, Kathi