news 2026/1/30 19:23:49

【time-rs】解释://! Error that occurred at some stage of parsing(error/parse.rs)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【time-rs】解释://! Error that occurred at some stage of parsing(error/parse.rs)

这段Rust代码定义了一个解析错误的通用枚举类型Parse,用于表示在时间解析过程中可能发生的各种错误。它是时间解析库中的核心错误类型。

枚举定义

#[non_exhaustive]#[allow(variant_size_differences, reason ="only triggers on some platforms")]#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumParse{TryFromParsed(TryFromParsed),ParseFromDescription(ParseFromDescription),#[non_exhaustive]#[deprecated( since ="0.3.28", note ="no longer output. moved to the `ParseFromDescription` variant")]UnexpectedTrailingCharacters{#[doc(hidden)]never:Infallible,},}

属性说明:

  1. #[non_exhaustive]

    • 表示枚举未来可能添加新变体
    • 强制用户代码使用穷尽匹配,保持向后兼容
  2. #[allow(variant_size_differences)]

    • 允许变体大小不同(因为包含Infallible类型)
    • reason属性说明:仅在某些平台上触发
  3. #[derive(...)]

    • 实现了DebugCloneCopyPartialEqEq等常见trait

变体详解

1.TryFromParsed(TryFromParsed)

  • 表示在从解析结果转换到目标类型时发生的错误
  • 例如:解析出的日期时间值超出目标类型的有效范围

2.ParseFromDescription(ParseFromDescription)

  • 表示根据格式描述进行解析时发生的错误
  • 例如:输入字符串与格式描述不匹配

3.UnexpectedTrailingCharacters(已弃用)

#[deprecated(since ="0.3.28", note ="...")]UnexpectedTrailingCharacters{#[doc(hidden)]never:Infallible,}
  • 已弃用:从 0.3.28 版本开始不再使用
  • 迁移:功能已移至ParseFromDescription变体
  • Infallible:永不实例化的类型,确保该变体无法构造
  • 设计目的:保持API兼容性,同时逐步移除旧功能

Display trait 实现

implfmt::DisplayforParse{fnfmt(&self,f:&mutfmt::Formatter<'_>)->fmt::Result{matchself{Self::TryFromParsed(err)=>err.fmt(f),Self::ParseFromDescription(err)=>err.fmt(f),#[allow(deprecated)]Self::UnexpectedTrailingCharacters{never}=>match*never{},}}}

实现特点

  • 委托给内部错误的Display实现
  • 对于已弃用变体,使用match *never {}保证编译通过
  • #[allow(deprecated)]允许使用已弃用的变体模式

Error trait 实现

implcore::error::ErrorforParse{fnsource(&self)->Option<&(dyncore::error::Error+'static)>{matchself{Self::TryFromParsed(err)=>Some(err),Self::ParseFromDescription(err)=>Some(err),#[allow(deprecated)]Self::UnexpectedTrailingCharacters{never}=>match*never{},}}}

特点

  • 实现source()方法,提供错误的根本原因
  • 支持错误链(error chain)
  • 同样处理了已弃用变体

与内部错误类型的转换

TryFromParsed转换到Parse

implFrom<TryFromParsed>forParse{fnfrom(err:TryFromParsed)->Self{Self::TryFromParsed(err)}}

Parse尝试转换到TryFromParsed

implTryFrom<Parse>forTryFromParsed{typeError=error::DifferentVariant;fntry_from(err:Parse)->Result<Self,Self::Error>{matcherr{Parse::TryFromParsed(err)=>Ok(err),_=>Err(error::DifferentVariant),}}}

ParseFromDescription转换到Parse

implFrom<ParseFromDescription>forParse{fnfrom(err:ParseFromDescription)->Self{Self::ParseFromDescription(err)}}

Parse尝试转换到ParseFromDescription

implTryFrom<Parse>forParseFromDescription{typeError=error::DifferentVariant;fntry_from(err:Parse)->Result<Self,Self::Error>{matcherr{Parse::ParseFromDescription(err)=>Ok(err),_=>Err(error::DifferentVariant),}}}

转换模式总结

  • From<T>:总是成功,向上转换
  • TryFrom<Parse>:可能失败,向下转换
  • DifferentVariant:当错误类型不匹配时返回

与 crate::Error 的转换

向上转换:Parsecrate::Error

implFrom<Parse>forcrate::Error{fnfrom(err:Parse)->Self{matcherr{Parse::TryFromParsed(err)=>Self::TryFromParsed(err),Parse::ParseFromDescription(err)=>Self::ParseFromDescription(err),#[allow(deprecated)]Parse::UnexpectedTrailingCharacters{never}=>matchnever{},}}}

处理已弃用变体

  • 对于UnexpectedTrailingCharacters,使用match never {}保证不会执行
  • 确保编译通过,即使变体已弃用

向下转换:crate::ErrorParse

implTryFrom<crate::Error>forParse{typeError=error::DifferentVariant;fntry_from(err:crate::Error)->Result<Self,Self::Error>{matcherr{crate::Error::ParseFromDescription(err)=>Ok(Self::ParseFromDescription(err)),#[allow(deprecated)]crate::Error::UnexpectedTrailingCharacters{never}=>matchnever{},crate::Error::TryFromParsed(err)=>Ok(Self::TryFromParsed(err)),_=>Err(error::DifferentVariant),}}}

使用场景示例

解析时间字符串

usetime::format_description;usetime::parsing::Parse;fnparse_datetime(input:&str)->Result<OffsetDateTime,Parse>{letformat=format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]")?;letparsed=PrimitiveDateTime::parse(input,&format)?;Ok(parsed.into())}

错误处理

matchparse_datetime("2023-13-01 25:00:00"){Ok(dt)=>println!("解析成功: {}",dt),Err(Parse::ParseFromDescription(err))=>{eprintln!("格式解析错误: {}",err);}Err(Parse::TryFromParsed(err))=>{eprintln!("类型转换错误: {}",err);}}

设计特点

1. 分层错误处理

crate::Error ├── Parse │ ├── TryFromParsed │ └── ParseFromDescription └── Other errors...

2. 向后兼容性

  • 使用#[deprecated]Infallible平滑过渡
  • #[non_exhaustive]保护未来扩展

3. 类型安全

  • 双向转换确保类型安全
  • 使用TryFrom进行安全的错误类型提取

4. 性能优化

  • #[inline]提示内联优化
  • 大部分类型实现Copy,减少分配

与其他错误类型的关系

错误类型层级用途
crate::Error顶级所有错误的容器
Parse中间层解析相关错误
TryFromParsed具体层转换错误
ParseFromDescription具体层格式解析错误

这种设计提供了灵活的错误处理机制,既支持通用的错误处理,也支持精确的错误类型匹配。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/1/24 16:49:34

启天 M 系列 Smart Power On/Fast boot 置灰?2 步解锁修改权限!

使用联想启天 M 系列商用台式机时&#xff0c;不少用户会遇到一个棘手问题&#xff1a;想要开启或关闭 Smart Power On&#xff08;智能开机&#xff09;和 Fast boot&#xff08;快速启动&#xff09;功能&#xff0c;却发现设置选项呈灰色锁定状态&#xff0c;无法点击修改。…

作者头像 李华
网站建设 2026/1/28 14:20:35

告别繁琐问卷设计!百考通AI智能助手,5分钟生成专业调研问卷

在数据驱动决策的今天&#xff0c;无论是市场部门洞察用户心声&#xff0c;HR团队评估员工满意度&#xff0c;还是产品经理优化产品体验&#xff0c;一份设计精良、逻辑严谨的调查问卷都是获取一手信息、做出科学判断的基石。然而&#xff0c;从零开始构思问题、设置选项、排版…

作者头像 李华
网站建设 2026/1/24 22:00:33

百考通AI:你的智能学术助手,让毕业论文写作化繁为简

在学业的冲刺阶段&#xff0c;面对堆积如山的文献、复杂的研究方法和令人头疼的开题报告&#xff0c;你是否也感到力不从心&#xff1f;别担心&#xff0c;百考通AI&#xff08;https://www.baikaotongai.com&#xff09;为你而来&#xff0c;它不是简单的工具&#xff0c;而是…

作者头像 李华
网站建设 2026/1/29 19:09:43

IntelliJ IDEA 2025.3 正式发布

因公众号更改推送规则&#xff0c;请点“在看”并加“星标”第一时间获取精彩技术分享点击关注#互联网架构师公众号&#xff0c;领取架构师全套资料 都在这里0、2T架构师学习资料干货分上一篇&#xff1a;2T架构师学习资料干货分享大家好&#xff0c;我是互联网架构师&#xff…

作者头像 李华
网站建设 2026/1/30 4:23:53

MyBatis-Flex 来了!完爆MyBatis-Plus?

因公众号更改推送规则&#xff0c;请点“在看”并加“星标”第一时间获取精彩技术分享点击关注#互联网架构师公众号&#xff0c;领取架构师全套资料 都在这里0、2T架构师学习资料干货分上一篇&#xff1a;2T架构师学习资料干货分享大家好&#xff0c;我是互联网架构师&#xff…

作者头像 李华
网站建设 2026/1/27 10:06:13

神经紧张素受体SORT1

神经紧张素受体&#xff08;NRT3&#xff09;又称为糖蛋白95&#xff08;Gp95&#xff09;或分选蛋白&#xff08;SORT1&#xff09;&#xff0c;它作为高尔基腔内的分选受体和细胞表面的清除受体发挥作用。通过不依赖于甘露糖-6-磷酸受体&#xff08;M6PR&#xff09;的途径将…

作者头像 李华