'Checking if even on a generic type in Rust [duplicate]

I have the following code

pub fn evens<T>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
    iter.filter(|x| x % 2 == 0)
}

But it doesn't compile because

error[E0369]: cannot mod `&T` by `{integer}`
  --> src/lib.rs:10:23
   |
10 |     iter.filter(|x| x % 2 == 0)
   |                     - ^ - {integer}
   |                     |
   |                     &T
   |
help: consider restricting type parameter `T`
   |
9  | pub fn evens<T: std::ops::Rem<Output = {integer}>>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
   |               +++++++++++++++++++++++++++++++++++

What do I need to do to operate on T type to check if it is even? I tried casting T but that didn't work.

I also tried using the suggested function signature in the error message, but that led to a whole host of new problems:

error: cannot constrain an associated constant to a value
 --> src/lib.rs:9:31
  |
9 | pub fn evens<T: std::ops::Rem<Output = {integer}>>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
  |                               ------^^^---------
  |                               |        |
  |                               |        ...cannot be constrained to this value
  |                               this associated constant...

error[E0282]: type annotations needed
  --> src/lib.rs:10:10
   |
10 |     iter.filter(|x| x % 2 == 0)
   |          ^^^^^^ cannot infer type
   |
   = note: type must be known at this point

error[E0599]: no method named `filter` found for type parameter `impl Iterator<Item = T>` in the current scope
  --> src/lib.rs:10:10
   |
10 |     iter.filter(|x| x % 2 == 0)
   |          ^^^^^^ method not found in `impl Iterator<Item = T>`
   |
   = note: `iter` is a function, perhaps you wish to call it
   = help: items from traits can only be used if the type parameter is bounded by the trait


Solution 1:[1]

Assuming you want to filter on INDEX (and not VALUE), then the following code works:

pub fn evens<T>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
    iter.enumerate().filter(|(i, _)| i % 2 == 0).map(|(_, e)| e)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nate Houk