通达信缠论可视化插件:3分钟快速上手的终极免费工具
2026/6/3 22:28:06
这段Rust代码定义了一个格式化错误类型,用于处理时间或数据结构格式化过程中的各种错误情况。
用于表示在格式化数据结构(特别是时间相关结构)时可能发生的各种错误。
#[non_exhaustive]#[derive(Debug)]pubenumFormat{/// 被格式化的类型包含的信息不足以格式化某个组件#[non_exhaustive]InsufficientTypeInformation,/// 指定组件的值无法格式化为请求的格式/// 仅在使用的格式字符串时返回InvalidComponent(&'staticstr),/// 提供的组件值超出范围ComponentRange(Box<error::ComponentRange>),/// 内部返回了 `std::io::Error` 值StdIo(io::Error),}特性说明:
#[non_exhaustive]: 表示枚举可能在未来版本中添加新的变体implfmt::DisplayforFormat{fnfmt(&self,f:&mutfmt::Formatter<'_>)->fmt::Result{matchself{Self::InsufficientTypeInformation=>f.write_str("..."),Self::InvalidComponent(component)=>write!(f,"..."),Self::ComponentRange(err)=>err.fmt(f),Self::StdIo(err)=>err.fmt(f),}}}fmt方法从其他错误类型转换到Format:
implFrom<error::ComponentRange>forFormat{fnfrom(err:error::ComponentRange)->Self{Self::ComponentRange(Box::new(err))}}implFrom<io::Error>forFormat{fnfrom(err:io::Error)->Self{Self::StdIo(err)}}ComponentRange和io::Error轻松转换为Format从Format尝试提取特定错误:
implTryFrom<Format>forerror::ComponentRange{fntry_from(err:Format)->Result<Self,Self::Error>{matcherr{Format::ComponentRange(err)=>Ok(*err),_=>Err(error::DifferentVariant),}}}implTryFrom<Format>forio::Error{fntry_from(err:Format)->Result<Self,Self::Error>{matcherr{Format::StdIo(err)=>Ok(err),_=>Err(error::DifferentVariant),}}}Format包含特定错误类型,可以提取出来DifferentVariant错误implcore::error::ErrorforFormat{fnsource(&self)->Option<&(dyncore::error::Error+'static)>{matchself{Self::InsufficientTypeInformation|Self::InvalidComponent(_)=>None,Self::ComponentRange(err)=>Some(&**err),Self::StdIo(err)=>Some(err),}}}Errortraitsource()方法提供了错误的根本原因(对于包装的错误类型)implFrom<Format>forcrate::Error{fnfrom(original:Format)->Self{Self::Format(original)}}implTryFrom<crate::Error>forFormat{fntry_from(err:crate::Error)->Result<Self,Self::Error>{matcherr{crate::Error::Format(err)=>Ok(err),_=>Err(error::DifferentVariant),}}}#[cfg(feature ="serde")]implFormat{pubfninto_invalid_serde_value<S:serde_core::Serializer>(self)->S::Error{useserde_core::ser::Error;S::Error::custom(self)}}serde功能时可用Format错误转换为Serde序列化错误source()方法支持错误链InsufficientTypeInformation: 零大小InvalidComponent: 仅存储静态字符串引用ComponentRange: 使用Box避免枚举大小过大#[non_exhaustive]保持API向后兼容serde功能假设有一个时间格式化函数:
fnformat_time(time:&Time,format:&str)->Result<String,Format>{if!time.has_timezone(){returnErr(Format::InsufficientTypeInformation);}iftime.hour()>23{returnErr(error::ComponentRange.into());// 自动转换为Format}// 格式化逻辑...Ok(formatted_string)}这种设计允许: