为什么 Unsigned 特征不会自动给出例如Rust 的唯一特征?

Why doesn't the Unsigned trait automatically give e.g. the One trait in Rust?

我想编写形式为

的泛型函数
fn my_function<T: num::Unsigned>(T: number) -> T

为了将它们用于所有无符号整数类型,所以u8-u128。 但是,我经常想做类似

的事情
let n = number + 1;

let mut n = number;
number -= 1;

在函数体内。现在,每次我使用类似的东西时,Rust 都会告诉我 std::ops::SubAssign-trait、std::cmp::PartialOrd-trait 等没有为 T.

实现

有没有一种简单的方法可以指定我的号码只是 u8-u128 类型中的一种,从而享有所有这些特征?为什么 Rust 编译器不清楚这一点,即没有 PartialOrd 特征的 Unsigned 类型的示例是什么?

编辑:澄清一下:我想要的是一种说法“T 必须具有其中一种类型 u8...u128(也许 BigUInt)" 然后让 Rust 自动看到 "因为 T 是其中一种类型,必须为 T 实现以下特征:std::cmp::PartialOrd, std::ops::SubAssign, ..."

相反,T: Unsigned确实暗示T: OneUnsigned is a super trait over Num 优于 ZeroOne 等:

pub trait Unsigned: Num { }
pub trait Num: Zero + One + NumOps<Self, Self> + PartialEq<Self> { ... }

要理解的关键是 1T::one() 不同。这适用于例如:

use num::Unsigned; // 0.4.0

fn my_function<T: Unsigned>(number: T) -> T {
    number + T::one()
}

NumOps 特性意味着定义了各种算术运算符,但仅在 T 之间。文字 1 可能不是 TT 可能类似于 BigUint.


What I would love is a way to say "T has to have one of the types u8...u128 (and maybe BigUInt)" and then have Rust to automatically see "since T is of one of those types, the following traits have to be implemented for T: std::cmp::PartialOrd, std::ops::SubAssign, ..."

这不是特征设计的工作方式。 Traits 可以在外部类型上实现,所以即使 Unsigned 只为这些类型实现 now,其他一些箱子我为他们的类型实现它,这些类型没有所有u8...u128 等的相同属性

相反,您应该约束 T 以获得函数运行所需的属性。所以你必须明确。