在 Rust 中,我需要什么特征来比较泛型和整数

In Rust, what trait do I need to compare a generic to an integer

如何将计算结果与一般计算结果进行比较? T 始终是某种无符号整数类型(u64、u32 等),因此代码段中的

fn reproduction<T>(val: T) -> bool
where
    T: PartialOrd
{
    let var_of_type_integer = 7; // actually the result of a calculation
    if val < var_of_type_integer { // ERROR: expected type parameter, found integer
        return true;
    }
    false
}

PartialOrd 特征可以采用通用参数来指定可以比较的类型:

pub trait PartialOrd<Rhs = Self>: PartialEq<Rhs>
where
    Rhs: ?Sized,
{
    // ...
}

所以这个编译:

pub fn reproduction<T>(val: T) -> bool
where
    T: PartialOrd<i32>,
{
    let var_of_type_integer = 7;
    if val < var_of_type_integer {
        return true;
    }
    false
}

当然只有一半的故事能够编译。当您或用户实际调用具有某种具体类型值的函数时,该类型必须满足指定的 PartialOrd<i32> 特征界限。