2026/6/11 6:06:59
网站建设
项目流程
陕西网渭南站,做百度推广网站排名,酒泉网站建设服务,网站优化软件方案这是一个 Rust 时间库中的组件范围错误类型#xff0c;用于表示时间组件#xff08;如年、月、日、时、分、秒等#xff09;值超出允许范围的情况。
1. 结构体定义
pub struct ComponentRange {pub(crate) name: static str, // 组件名称pub(crate) minimum: i64…这是一个 Rust 时间库中的组件范围错误类型用于表示时间组件如年、月、日、时、分、秒等值超出允许范围的情况。1. 结构体定义pubstructComponentRange{pub(crate)name:staticstr,// 组件名称pub(crate)minimum:i64,// 最小值包含pub(crate)maximum:i64,// 最大值包含pub(crate)value:i64,// 提供的值pub(crate)conditional_message:Optionstaticstr,// 条件性错误信息}设计选择使用i64作为数值类型因为它是最窄的、能满足所有用例的整数类型避免了泛型参数的需要。2. 主要方法查询方法// 获取组件名称leterrComponentRange{name:hour,minimum:0,maximum:23,value:25,conditional_message:None};assert_eq!(err.name(),hour);// 检查是否为条件性错误letconditional_errComponentRange{name:day,minimum:1,maximum:28,value:30,conditional_message:Some(in February)};assert!(conditional_err.is_conditional());3. 特征实现PartialEq 和 HashimplPartialEqforComponentRange{fneq(self,other:Self)-bool{self.nameother.nameself.minimumother.minimumself.maximumother.maximumself.valueother.value// 注意比较时只检查是否有条件信息不比较具体内容self.conditional_message.is_some()other.conditional_message.is_some()}}implhash::HashforComponentRange{fnhashH:hash::Hasher(self,state:mutH){// 同样的逻辑条件信息只检查是否存在}}重要设计比较和哈希时只检查conditional_message是否存在不比较其内容。这是因为条件信息只是为了更好的错误提示不影响错误的本质。Display 特征implfmt::DisplayforComponentRange{fnfmt(self,f:mutfmt::Formatter_)-fmt::Result{// 基本格式hour must be in the range 0..23write!(f,{} must be in the range {}..{},self.name,self.minimum,self.maximum)?;// 如果有条件信息追加in FebruaryifletSome(message)self.conditional_message{write!(f, {message})?;}Ok(())}}示例输出hour must be in the range 0..23day must be in the range 1..28 in February4. 与 crate::Error 的转换双向转换// ComponentRange - crate::ErrorimplFromComponentRangeforcrate::Error{fnfrom(original:ComponentRange)-Self{Self::ComponentRange(original)}}// crate::Error - ComponentRange (可能失败)implTryFromcrate::ErrorforComponentRange{typeErrorerror::DifferentVariant;fntry_from(err:crate::Error)-ResultSelf,Self::Error{matcherr{crate::Error::ComponentRange(err)Ok(err),_Err(error::DifferentVariant),// 如果不是 ComponentRange 变体}}}5. Serde 集成可选特性作为 Expected trait#[cfg(feature serde)]implserde_core::de::ExpectedforComponentRange{fnfmt(self,f:mutfmt::Formatter_)-fmt::Result{write!(f,a value in the range {}..{},self.minimum,self.maximum)}}注意文档指出这个实现是废弃的将在未来的破坏性更新中移除。转换为反序列化错误#[cfg(feature serde)]implComponentRange{pub(crate)fninto_de_errorE:serde_core::de::Error(self)-E{E::invalid_value(serde_core::de::Unexpected::Signed(self.value),self)}}6. Error 特征实现implcore::error::ErrorforComponentRange{}这使得ComponentRange可以作为标准错误类型使用可以向上传播。7. 使用场景示例创建时间时验证组件fncreate_time(hour:u8,minute:u8,second:u8)-ResultTime,ComponentRange{ifhour23{returnErr(ComponentRange{name:hour,minimum:0,maximum:23,value:hourasi64,conditional_message:None,});}// ... 其他验证Ok(Time::from_hms(hour,minute,second)?)}条件性范围错误fnvalidate_day(month:Month,day:u8)-Result(),ComponentRange{letmax_daysdays_in_month(month);ifdaymax_days{returnErr(ComponentRange{name:day,minimum:1,maximum:max_daysasi64,value:dayasi64,conditional_message:Some(format!(in {},month.name()).leak()),});}Ok(())}8. 设计亮点明确的错误信息包含组件名、范围、实际值条件性范围支持处理像2月的天数这样的条件限制高效的内存使用使用静态字符串引用避免分配完整的错误集成支持标准库的 Error trait序列化友好可选支持 Serde 集成类型安全从crate::Error转换时需要显式处理9. 典型错误流matchTime::from_hms(25,0,0){Ok(time){/* 使用时间 */}Err(ComponentRange{name:hour,minimum,maximum,value,..}){println!(小时值 {} 超出范围 {}..{},value,minimum,maximum);}Err(other_error){/* 处理其他错误 */}}这个错误类型是时间库中验证逻辑的核心部分确保所有时间组件都在有效范围内并提供清晰的错误信息以便调试。