[英]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::Err
是FromStr
特征的关联类型 。 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. 但是,一致性规则不允许此实现-与标准库中任何类型
T
的From<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 {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.