For a function like this:
fn generate_even(a: i32, b: i32) -> impl Iterator<Item = i32> {
(a..b).filter(|x| x % 2 == 0)
}
I want to make it generic, instead of the concrete type i32 I want to have any type that is range-able and provide a filter implementation.
Tried the formula below without success:
fn generate_even(a: T, b: T) -> impl Iterator<Item = T>
where T: // range + filter + what to put here?
{
(a..b).filter(|x| x % 2 == 0)
}
How can something like this be implemented?
playground
The hardest part of the solution is implementing
x % 2 == 0in a generic way because by default Rust interprets integer literals asi32s but you want your function to be generic across all possible integer types, which means you have to produce a2and0value of whatever integer type the caller specifies, and the simplest way to do that is to boundTbyFrom<u8>which allows us to transform any value from0to256into any integer type (withi8being the only exception). The above solution is generic and works for all integer types excepti8.