【typenum】30 类型级别的取负(Neg)
一、源码
三部分代码共同实现了一个类型级别的取负操作。
- 别名(src/operator_aliases.rs)
/// Alias for the associated type of `Neg`: `Negate<A> = <A as Neg>::Output`
pub type Negate<A> = <A as Neg>::Output;
- 整数实现取负
/// `-Z0 = Z0`
impl Neg for Z0 {type Output = Z0;#[inline]fn neg(self) -> Self::Output {Z0}
}/// `-PInt = NInt`
impl<U: Unsigned + NonZero> Neg for PInt<U> {type Output = NInt<U>;#[inline]fn neg(self) -> Self::Output {NInt::new()}
}/// `-NInt = PInt`
impl<U: Unsigned + NonZero> Neg for NInt<U> {type Output = PInt<U>;#[inline]fn neg(self) -> Self::Output {PInt::new()}
}
- 数组实现取负
// ---------------------------------------------------------------------------------------
// Negate an array
use core::ops::Neg;impl Neg for ATerm {type Output = ATerm;#[inline]fn neg(self) -> Self::Output {ATerm}
}impl<V, A> Neg for TArr<V, A>
whereV: Neg,A: Neg,
{type Output = TArr<Negate<V>, Negate<A>>;#[inline]fn neg(self) -> Self::Output {TArr {first: -self.first,rest: -self.rest,}}
}
二、别名定义 (src/operator_aliases.rs)
/// Alias for the associated type of `Neg`: `Negate<A> = <A as Neg>::Output`
pub type Negate<A> = <A as Neg>::Output;
解释:
-
这是一个类型别名,用于简化代码
-
Negate 等价于 ::Output(即类型A实现Neg特质后的输出类型)
-
作用:让代码更简洁易读,避免重复写冗长的关联类型语法
三、整数的取负实现
这部分为三种整数类型实现了 Neg 特质(取负操作):
/// `-Z0 = Z0`
impl Neg for Z0 { // 为零实现取负type Output = Z0; // 结果还是零#[inline]fn neg(self) -> Self::Output {Z0 // 返回零本身}
}/// `-PInt = NInt`
impl<U: Unsigned + NonZero> Neg for PInt<U> { // 为正整数实现取负type Output = NInt<U>; // 结果变为负整数#[inline]fn neg(self) -> Self::Output {NInt::new() // 创建对应的负整数}
}/// `-NInt = PInt`
impl<U: Unsigned + NonZero> Neg for NInt<U> { // 为负整数实现取负type Output = PInt<U>; // 结果变为正整数#[inline]fn neg(self) -> Self::Output {PInt::new() // 创建对应的正整数}
}
数学规则:
-
-0 = 0
-
-(正数) = 负数
-
-(负数) = 正数
四、数组的取负实现
这部分为类型级别数组实现了 Neg 特质:
impl Neg for ATerm { // 空数组的取负type Output = ATerm; // 结果还是空数组#[inline]fn neg(self) -> Self::Output {ATerm // 返回空数组本身}
}impl<V, A> Neg for TArr<V, A> // 非空数组的取负
whereV: Neg, // 要求数组元素类型可取负A: Neg, // 要求剩余数组类型可取负
{type Output = TArr<Negate<V>, Negate<A>>; // 结果为每个元素取负的新数组#[inline]fn neg(self) -> Self::Output {TArr {first: -self.first, // 对第一个元素取负rest: -self.rest, // 对剩余数组递归取负}}
}
递归处理过程:
对于数组 [a, b, c](实际表示为 TArr(a, TArr(b, TArr(c, ATerm)))):
-
取负得到:TArr(-a, -[b, c])
-
递归:TArr(-a, TArr(-b, -[c]))
-
递归:TArr(-a, TArr(-b, TArr(-c, -ATerm)))
-
最终:TArr(-a, TArr(-b, TArr(-c, ATerm))) 即 [-a, -b, -c]
五、整体设计模式
这是一个典型的递归类型级别编程示例:
-
基础情况:空数组取负还是空数组
-
递归情况:非空数组取负 = 第一个元素取负 + 剩余数组递归取负
类型安全保证:
-
编译时确保所有数组元素类型都实现了 Neg 特质
-
编译时完成整个数组的取负操作,无运行时开销
用途: 在编译时进行数学运算验证、符号处理等类型级计算。