简体   繁体   English

为另一个特征项目类型实现特征

[英]Implement a trait for another trait Item type

I need to convert a parse error to my own Error type while returning Result. 返回Result时,我需要将解析错误转换为我自己的Error类型。 Simplified, it looks like the following: 简化后,它看起来如下所示:

enum MyError {
    Parse,
    ...,
}

fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    Ok(s.parse::<R>()?)
}

For above to work From trait should be implemented. 为了上述工作,应实施特质。 This doesn't work: 这不起作用:

impl From<std::str::FromStr::Err> for MyError {
    fn from(e: std::str::FromStr::Err) -> MyError {
        MyError::Parse
    }
}

The compiler diagnostics: 编译器诊断:

help: use fully-qualified syntax: `<Type as std::str::FromStr>::Err`

But I don't know the exact Type here. 但是我不知道确切的Type The whole point is to allow conversion from all possible errors. 关键是要允许所有可能的错误转换。

The type FromStr::Err is an associated type of the FromStr trait. 类型FromStr::ErrFromStr特征的关联类型 Every implementation of FromStr has its own associated type, and this type is completely unconstrained – it could be any type at all. FromStr每个实现都有其自己的关联类型,并且该类型是完全不受约束的-可以是任何类型。 This means you would need a conversion from any type to MyError to achieve what you want: 这意味着您需要从任何类型到MyError的转换才能实现所需的功能:

impl<T> From<T> for MyError {
    fn from(e: T) -> MyError {
        MyError::Parse
    }
}

However, this implementation is disallowed by the coherence rules – it conflicts with the implementation of From<T> for any type T in the standard library. 但是,一致性规则不允许此实现-与标准库中任何类型TFrom<T>的实现冲突。 And even if this implementation was allowed, it wouldn't really do what you want – any error type would be converted to MyError::Parse , not just parse errors. 即使允许这种实现,它也不会真正做您想要的事情– 任何错误类型都将转换为MyError::Parse ,而不仅仅是解析错误。

One possible workaround is to introduce a marker trait for parse error types: 一种可能的解决方法是为解析错误类型引入标记特征:

trait ParseError {}

impl<T: ParseError> From<T> for MyError {
    fn from(e: T) -> MyError {
        MyError::Parse
    }
}

You can then implement this marker trait for all parse error types: 然后,您可以为所有解析错误类型实现此标记特征:

impl ParseError for std::str::ParseBoolError {}
impl ParseError for std::num::ParseFloatError {}
impl ParseError for std::num::ParseIntError {}
impl ParseError for std::net::AddrParseError {}
impl ParseError for std::char::ParseCharError {}

If you're discarding the parse error anyway, use map_err to change the error locally: 如果仍然要丢弃解析错误,请使用map_err在本地更改错误:

fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    let _ = s.parse::<R>().map_err(|_| MyError::Parse)?;
    Ok(())
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为自定义错误类型实现From trait? - How to implement From trait for custom error types? 惯用的 Rust:字符串标记化应该是 function、特殊特征还是 TryFrom 特征? - Idiomatic Rust: should string tokenization be a function, a special trait or a TryFrom trait? 如何在 Rust 中隐藏特征实现 - How to hide trait implementation in Rust 如何使用 rust Try trait with Option NoneError? - How can I use rust Try trait with Option NoneError? 为什么? 运算符报错误“特征绑定NoneError:错误不满足”? - Why does the ? operator report the error "the trait bound NoneError: Error is not satisfied"? 有没有办法在任意 `&amp;dyn std::error::Error` 特征对象上获取 SNAFU 的 `.backtrace()`? - Is there a way to get SNAFU's `.backtrace()` on arbitrary `&dyn std::error::Error` trait objects? 如何在Scala中以单数Some特质递归地构造列表? - How can you recursively construct a list inside of a singular Some trait in Scala? 扩展失败类型的结果时,为什么会得到“该方法存在,但以下特征范围不满足”的信息? - Why do I get “the method exists but the following trait bounds were not satisfied” when extending Result for failure types? 为什么Rust编译器不能使用From特性将库错误转换为我的错误? - Why does the Rust compiler not convert from a library error to my error using the From trait? 为什么这些错误不会自动转换为我的自定义错误,即使它们同时实现了 std::error::Error 特征? - Why these errors are not automagically converted to my custom error even if they are implementing both std::error::Error trait?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM