Comparing zero to generic

I thought this would be correct,
The error I get is at l == 0:
expected type parameter T, found integer


use std::fmt::Debug;
use num::Zero;

fn main() {
    let i: i32 = 7;

fn is_working<T>(l: T)
    T: Debug + Zero + std::cmp::PartialEq,
    if l == 0 {
        println!("{:#?}", ("great"));

Rust does not coerce 0 into anything other than concrete builtin integer types.

You need to use the API of the Zero trait: if l.is_zero() or l == T::zero().

Thank you.

I was trying l == Zero, l == T::Zero, num::Zero, many combos

I'm not very good at reading the docs. Did you learn by looking at them and just practice ? I need to learn to read it.

I think I have to learn more about Traits. It's all about traits.

In this case, yes, it's all about traits :slight_smile:

The is_zero method is found relatively easily, on the page of the Zero trait. The other method (zero) is also found there, and it's important to notice that it is a static method: it doesn't take a self. So you can call it on the type as T::zero().

I believe the zero could also have been defined as an associated constant on the trait, in that case it would have been e.g. T::ZERO.

1 Like

Indeed, or even T::_0. Nowadays, with const generics, we could even imagine a fully general <T as Get<0>>::VALUE. Another approach being to have From<U0> (or From<_0> if renamed), with U0 being a type-level equivalent of 0, such as ::typenum::U0 or U::<0> for some struct U<const N: u32>;. Many possibilites :slightly_smiling_face: