如何手动返回Result(),Box< dyn Error>&gt ;? [英] How to manually return a Result<(), Box<dyn Error>>?

查看:522
本文介绍了如何手动返回Result(),Box< dyn Error>&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在条件为真的情况下,我想从函数返回错误:

I want to return an error from a function in case a condition is true:

use std::error::Error;

pub fn run() -> Result<(), Box<dyn Error>> {
    // -- snip ---

    if condition {
        // return error
    }

    // -- snip --

    Ok(())
}

fn main() {}

我可能没有类型系统的基础知识,但是在我所见之处,人们都在使用运算符,所以我不知道要返回什么类型。

I probably don't have the basics of the typesystem down, but everywhere I looked people use the ? operator, so I can't figure out what type to return.


  1. 是否可以仅返回这样的错误?

  2. 是否有更好的方法来处理此逻辑?


推荐答案

错误是一个特征,您想返回一个特征对象(请注意 dyn 关键字),因此您需要实现此特征:

Error is a trait and you want to return a trait object (note the dyn keyword), so you need to implement this trait:

use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct MyError(String);

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "There is an error: {}", self.0)
    }
}

impl Error for MyError {}

pub fn run() -> Result<(), Box<dyn Error>> {
    let condition = true;

    if condition {
        return Err(Box::new(MyError("Oops".into())));
    }

    Ok(())
}

fn main() {
    if let Err(e) = run() {
        println!("{}", e); // "There is an error: Oops"
    }
}




  • 创建您自己的错误类型

  • 实施调试显示,然后执行错误

  • 如果有错误,请返回 Result Err 变体。

    • Create your own error type,
    • Implement Debug, Display, then Error for it,
    • If there is an error, return the Err variant of Result.
    • 我建议您使用失败删除所有错误样板:

      I advise you to use failure that remove all the error boilerplate:

      #[derive(Fail, Debug)]
      #[fail(display = "There is an error: {}.", _0)]
      struct MyError(String);
      

      -

      请注意,如果您如果出现 Error ,则可以返回所需的任何类型,只要它实现了 Error 。这包括 std 中的错误类型。

      Note that if you expect an Error, you can return whatever type you want, given that it implements Error. This includes the error types in std.

      这篇关于如何手动返回Result(),Box&lt; dyn Error&gt;&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆