当前位置: 首页 > news >正文

【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 类型相同

三、代码结构

  1. Trait 定义

pub trait Same<Rhs = Self> {type Output;
}
  • Rhs = Self:默认泛型参数,使得 Same 可以不带参数使用

  • Output:关联类型,用于返回结果

  1. 实现

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 时才进行类型检查,这使得:

  • 定义类型别名不会立即报错

  • 只有在实际使用时才会触发编译错误

七、实际用途

  1. 宏编程

// 在宏中可以统一处理运算符,由 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)和高级类型系统操作。

http://www.dtcms.com/a/343531.html

相关文章:

  • Esp32基础(⑩超声波测距模块)
  • Pycharm SSH连接
  • Wireshark数据包波形绘制异常
  • [RestGPT] docs | RestBench评估 | 配置与环境
  • 【51单片机】【protues仿真】基于51单片机16键电子琴系统
  • 【GPT入门】第51课 Conda环境迁移教程:将xxzh环境从默认路径迁移到指定目录
  • OpenAI 开源模型 gpt-oss 是在合成数据上训练的吗?一些合理推测
  • Mysql事务特性
  • python实现根据接口返回数据生成报告和图表
  • (第二十期下)超链接的更多分类
  • 医疗元宇宙:破解医疗困局与数字化变革路径
  • gRPC 服务发现选型对比
  • 基于STM32单片机的二维码识别物联网OneNet云仓库系统
  • 最小生成树的普利姆算法和克鲁斯卡尔算法
  • ABP vNext 速率限制在多租户场景落地
  • Leetcode 深度优先搜索 (13)
  • Leetcode 深度优先搜索 (12)
  • 20250821 圆方树总结
  • 通信基础理论
  • C语言基础习题——01
  • plantsimulation小知识25.08.21 对话框的使用方法
  • 深圳大学-计算机信息管理课程实验 C++ 自考模拟题
  • 【LeetCode】18. 四数之和
  • C语言:字符函数与字符串函数(2)
  • ORA-16331: container is not open ORA-06512: at “SYS.DBMS_LOGMNR“
  • Hexo 博客图片托管:告别本地存储,用 PicGo + GitHub 打造高速稳定图床
  • ArcMap 数据框裁剪(Data Frame Clip)操作教程
  • Service方法事务失效的原因是什么?
  • 2025-08-21 Python进阶8——命名空间作用域
  • PiscCode实现MediaPipe 的人体姿态识别:三屏可视化对比实现