news 2026/4/22 19:07:44

【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/4/23 10:21:40

开题报告不再“从零开始”!百考通AI智能助手,一键生成规范、详实的开题报告

对于每一位即将开启毕业设计或科研项目的学子而言&#xff0c;“开题报告”是整个研究工作的起点和蓝图。一份逻辑清晰、内容详实、格式规范的开题报告&#xff0c;不仅能帮助学生明确研究方向、厘清技术路线&#xff0c;更是指导老师审核项目可行性和评估工作量的重要依据。然…

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

百考通AI:你的智能文献管家,一键生成高质量综述,让学术研究事半功倍

在浩如烟海的学术文献中精准定位、高效整合并撰写一篇逻辑严谨、内容翔实的文献综述&#xff0c;是每一位科研工作者和学子都面临的巨大挑战。这不仅耗费大量时间精力&#xff0c;更考验着你的信息检索、归纳总结与批判性思维能力。当面对堆积如山的PDF文件和纷繁复杂的引文格式…

作者头像 李华
网站建设 2026/4/23 14:39:15

我在创业公司面试里画了 MVVM。对方问“为什么”。我当场宕机。

我有一支技术全面、经验丰富的小型团队&#xff0c;专注高效交付中等规模外包项目&#xff0c;有需要外包项目的可以联系我那场面试一点都不像面试。没有八股题&#xff0c;没有“请自我介绍”。 只有一张桌子、一块白板&#xff0c;以及一句像聊天一样随口的&#xff1a;“我们…

作者头像 李华
网站建设 2026/4/23 11:46:25

推荐一个开源神库!用一句话就能“变出”一套专业级PPT文稿!

大家好&#xff0c;我是菜哥&#xff01; 先问大家一个扎心的问题&#xff1a;你上一次为了赶一个PPT&#xff0c;熬到凌晨几点&#xff1f; 从确定主题、搜索素材、设计排版&#xff0c;到最后的配色调整、动画设置……一套高颜值的专业级PPT&#xff0c;往往需要耗费我们大量…

作者头像 李华