news 2026/5/30 13:28:05

【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/5/30 8:26:20

Ollama安装、下载模型

Ollama安装 Download Ollama on Windowshttps://ollama.com/downloadwindows直接下载&#xff0c;我下载了好久不知道啥原因 如果不想默认下载到C盘&#xff0c;参考博文如下&#xff0c;可自定义下载路径https://www.cnblogs.com/LaiYun/p/18696931https://www.cnblogs.com/…

作者头像 李华
网站建设 2026/5/26 11:09:43

抓住起涨信号:通达信〖一阳指二阳指〗主图+副图+选股指标,再度放量上行,一举突破关键压力位!

抓住起涨信号&#xff1a;通达信〖一阳指二阳指〗主图副图选股指标&#xff0c;再度放量上行&#xff0c;一举突破关键压力位&#xff01; 这套指标工具由主图、副图和选股指标三部分构成&#xff0c;旨在捕捉股价的关键转折信号&#xff0c;其核心功能围绕着“一阳指”与“二…

作者头像 李华
网站建设 2026/5/29 17:14:46

低代码物联网平台

物联网平台 - Thinglinks-iot ## &#x1f31f; 项目简介 一个功能完备、高可扩展的物联网平台&#xff0c;提供完整的设备接入、管理和数据处理解决方案。支持多种网络协议&#xff0c;具备强大的消息解析和实时告警能力&#xff0c;帮助企业快速构建物联网应用。 该项目现已纳…

作者头像 李华
网站建设 2026/5/22 1:35:31

智慧校园平台用户体验评估:如何做好师生满意度调查

✅作者简介&#xff1a;合肥自友科技 &#x1f4cc;核心产品&#xff1a;智慧校园平台(包括教工管理、学工管理、教务管理、考务管理、后勤管理、德育管理、资产管理、公寓管理、实习管理、就业管理、离校管理、科研平台、档案管理、学生平台等26个子平台) 。公司所有人员均有多…

作者头像 李华