【typenum】 19 类型相同检查(type_operators.rs片段)
一、源码
代码定义了一个 Rust trait Same,用于在类型系统中检查两个类型是否相同。
/// A **type operator** that ensures that `Rhs` is the same as `Self`, it is mainly useful
/// for writing macros that can take arbitrary binary or unary operators.
///
/// `Same` is implemented generically for all types; it should never need to be implemented
/// for anything else.
///
/// Note that Rust lazily evaluates types, so this will only fail for two different types if
/// the `Output` is used.
///
/// # Example
/// ```rust
/// use typenum::{Same, Unsigned, U4, U5};
///
/// assert_eq!(<U5 as Same<U5>>::Output::to_u32(), 5);
///
/// // Only an error if we use it:
/// # #[allow(dead_code)]
/// type Undefined = <U5 as Same<U4>>::Output;
/// // Compiler error:
/// // Undefined::to_u32();
/// ```
pub trait Same<Rhs = Self> {/// Should always be `Self`type Output;
}impl<T> Same<T> for T {type Output = T;
}
二、核心功能
类型相等检查:Same 确保当前类型(Self)与 Rhs 类型相同
三、代码结构
- Trait 定义
pub trait Same<Rhs = Self> {type Output;
}
-
Rhs = Self:默认泛型参数,使得 Same 可以不带参数使用
-
Output:关联类型,用于返回结果
- 实现
impl<T> Same<T> for T {type Output = T;
}
-
为所有类型 T 实现 Same
-
当 Self 和 Rhs 都是 T 时,Output 就是 T
五、工作原理
编译时类型检查
// ✅ 编译通过:U5 和 U5 类型相同
<U5 as Same<U5>>::Output // 返回 U5// ❌ 编译错误:U5 和 U4 类型不同(仅在访问 Output 时报错)
<U5 as Same<U4>>::Output // 编译错误
六、惰性求值特性
Rust 只在真正使用 Output 时才进行类型检查,这使得:
-
定义类型别名不会立即报错
-
只有在实际使用时才会触发编译错误
七、实际用途
- 宏编程
// 在宏中可以统一处理运算符,由 Same trait 确保类型安全
macro_rules! safe_operation {($lhs:ty, $op:ty, $rhs:ty) => {<$lhs as Same<$rhs>>::Output}
}
八、类型约束
可以作为其他 trait 的约束,确保操作数类型相同:
···rust
trait SafeAdd: Same {
type Sum;
}
···
九、总结
这是一个零开销的编译时类型检查工具:
-
✅ 运行时无性能损耗
-
✅ 编译时类型安全
-
✅ 支持泛型编程和宏扩展
-
✅ 利用 Rust 的 trait 系统和惰性求值特性
主要用于构建类型安全的领域特定语言(DSL)和高级类型系统操作。