[英]Passing boxed trait object to function accepting generic parameter implementing the trait
[英]Implementing a generic conversion from an object implementing the `Error` trait
我无法获得以下代码进行编译。
From
已经实现。 From
I的手动impl,则会收到From
not implemented的错误。 Error
它工作正常。 我想这是由于核心中的impl<T> From<T> for T
的空白impl impl<T> From<T> for T
。 我应该如何解决这个问题? 不实现Error
不是一个真正的选择。
代码( 游乐场 )
use std::fmt;
use std::io;
use std::error::Error;
#[derive(Debug)]
enum ErrorType {
Other(Box<Error>)
}
impl fmt::Display for ErrorType {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("not implemented")
}
}
impl Error for ErrorType {
fn description(&self) -> &str {
use self::ErrorType::*;
match *self {
Other(ref err) => err.description(),
}
}
}
impl<E: Error + 'static> From<E> for ErrorType {
fn from(other: E) -> Self {
ErrorType::Other(Box::new(other))
}
}
fn ret_io_err() -> Result<(), io::Error> {
Ok(())
}
fn ret_error_type() -> Result<(), ErrorType> {
try!(ret_io_err());
Ok(())
}
fn main() {}
你没有。
无论如何,这种实现有点无用。 这意味着所有其他错误类型将立即被装箱。 此时,您可能只是使用涉及Box<Error>
的现有转换并使用它 。
如果你想,实际上保留了统一的错误类型错误类型,您需要实现From
一次为他们每个人。 error-type
包可以帮助定义统一错误类型。
根据上面的评论,我发现这种方法只有作用:
impl<T: error::Error + 'static> From<Box<T>> for Error {
fn from(e: Box<T>) -> Self {
Error::Other(e)
}
}
要使用它你应该Box
错误:
try!(any_result().map_err(Box::new))
但是,如果您需要一般性错误(例如,对于用户定义的任务),您不需要使用枚举包装它,请尝试直接使用它:
trait AnyTask {
fn do_it(&self) -> Result<Success, Box<Error>>;
}
它可以使用try!
或.into()
无处不在。 这条路:
fn do_it(&self) -> Result<Succeed, Box<Error>> {
let row = try!(self.database.find_last());
if row.some_condition {
return Err("I don't like it!".into());
}
try!(self.database.insert(row));
Ok(Success)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.