How to manually return a Result<(), Box>?

后端 未结 4 952
傲寒
傲寒 2021-02-02 16:05

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

use std::error::Error;

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


        
4条回答
  •  离开以前
    2021-02-02 16:31

    A Result is an enum with two variants. To return either of them, you just use corresponding variants.

    fn foo(var: bool) -> Result<(), i32> {
        if var {
            Ok(()) //in fact this is std::result::Result::Ok
        } else {
            Err(-3) //in fact this is std::result::Result::Err
        }
    }
    

    The reason why you don't have to write std::result::Result::Ok is that it is in the prelude. As you can see, you don't have to stick to Box, but can return any type you want. It is a generic enum, with no restrictions.

    The ?-operator is a handy shortcut for early returns, so you don't have to be too verbose about results.

提交回复
热议问题