我想在所有函数中使用我的自定义错误类型,并且需要包装现有的标准错误,以便?
运算符成功。
这是我在做什么:
use std::{error::Error, fmt, fs};
#[derive(Debug)]
enum MyError {
A,
B,
}
impl fmt::Display for MyError {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
Ok(())
}
}
impl Error for MyError {
fn description(&self) -> &str {
""
}
}
trait NotMyError {}
impl<T: NotMyError + Error> From<T> for MyError {
fn from(_: T) -> MyError {
MyError::A
}
}
fn test() -> Result<(), MyError> {
fs::read_dir("test")?;
Ok(())
}
fn main() {}
编译器抱怨:
error[E0277]: the trait bound `std::io::Error: NotMyError` is not satisfied
--> src/main.rs:30:5
|
30 | fs::read_dir("test")?;
| ^^^^^^^^^^^^^^^^^^^^^ the trait `NotMyError` is not implemented for `std::io::Error`
|
= note: required because of the requirements on the impl of `std::convert::From<std::io::Error>` for `MyError`
= note: required by `std::convert::From::from`
最佳答案
有an excellent post about it。要获得错误的一流支持,您需要做两件事:
Error
trait。 std::convert::From
运算符无缝使用的错误类型实现?
(quick_error crate 可自动执行此操作)。 关于rust - 如何实现一个现有错误类型的错误包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958807/