I wrote a generic function to check if a given number is even or not:
use std::ops::Rem;
fn main() {
let x: u16 = 31;
let y: u32 = 40;
println!("x = {}, y = {}", is_even(x), is_even(y));
}
fn is_even<T: Rem<Output = T> + PartialEq>(n: T) -> bool {
n % 2 == 0
}
It produces the compiler error:
error[E0308]: mismatched types
--> src/main.rs:11:9
|
11 | n % 2 == 0
| ^ expected type parameter, found integral variable
|
= note: expected type `T`
found type `{integer}`
error[E0308]: mismatched types
--> src/main.rs:11:14
|
11 | n % 2 == 0
| ^ expected type parameter, found integral variable
|
= note: expected type `T`
found type `{integer}`
Since this is an error on using T
with concrete i32
values (2 and 0), I wrote another version of is_even
like this:
fn is_even<T: Rem<Output = T> + PartialEq> (n: T, with: T, output: T) -> bool {
n % with == output
}
This produces the desired output, but using is_even
is convoluted now: is_even(x, 2, 0)
. How to make my original version of is_even
work?
I do recognise that the modulo operator is generic enough and works with u16
and u32
values directly; a function like is_even
is not needed - but I wrote it to understand how generics work.