1

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.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
Fabian
  • 5,476
  • 4
  • 35
  • 46
  • 2
    The issue here is that the literal `2` can only represent primitive integer types, whereas you need to convert it to an arbitrary `T`. In my opinion, the easiest way to deal with this is to use the [`FromPrimitive`](https://docs.rs/num-traits/0.2.14/num_traits/cast/trait.FromPrimitive.html) trait then write something like `*x % T::from_u8(2) == T::zero()`. – Aplet123 Jan 05 '22 at 21:39
  • 1
    The answers in the linked question will handle the core of this issue, but you also need `T` to implement `Copy`, given how you're using `*x`. Otherwise, you'll get errors about moving `x`. So your generic will be something like `` – Rob Napier Jan 05 '22 at 21:46

0 Answers0