簡體   English   中英

從實現`Error`特征的對象實現泛型轉換

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM