I try to write a generic function in rust where I do an arithmetic calculation. Unfortunately the compiler does not allow to mix the T with an integer. The first non generic evens function works while the second does not compile.
use itertools::Itertools;
use num::Integer;
pub fn evens(iter: impl Iterator<Item = i32>) -> impl Iterator<Item = i32> {
iter.filter(|x| *x % 2 == 0)
}
pub fn evens_generic<T: Integer>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
iter.filter(|x| *x % 2 == 0)
}
fn main() {
let nums = vec!(1, 2, 3, 4, 5);
let filtered = evens_generic(nums.into_iter());
println!("{}", filtered.format(" "));
}
I get the compiler error
error[E0308]: mismatched types
--> src/main.rs:9:26
|
8 | pub fn evens_generic<T: Integer>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
| - this type parameter
9 | iter.filter(|x| *x % 2 == 0)
| ^ expected type parameter `T`, found integer
|
= note: expected type parameter `T`
found type `{integer}`
I understand that the traits I add will only limit to types that implement certain functions and not the type itself. But I would have expected if I limit to Integer it would be able to convert the parameter of the modulo function to the type T.