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

后端 未结 4 960
傲寒
傲寒 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:37

    Box is handy for types that implement it:

    use std::error::Error;
    fn main() -> Result<(), Box> {
       Err("March")?
    }
    

    but surprisingly, it doesnt work with all types:

    use std::error::Error;
    fn main() -> Result<(), Box> {
       // the trait `std::error::Error` is not implemented for `{integer}`
       Err(9)?
    }
    

    as a workaround, you can use what I call the Error Format idiom:

    use std::error::Error;
    fn main() -> Result<(), Box> {
       Err(format!("{}", 9))?
    }
    

    Note this has many variations, for example with literals you can do this:

    use std::error::Error;
    fn main() -> Result<(), Box> {
       Err(concat!(9))?
    }
    

    and also, you may not even need to use Box:

    fn main() -> Result<(), String> {
       Err(concat!(9))?
    }
    

    It can also be useful in cases where you normally dont need it. For example, this example below could work without it, but its useful as it adds the filename to the error, which normally isnt shown:

    use std::fs;
    fn main() -> Result<(), String> {
       let s = "a.rs";
       match fs::read_to_string(s) {
          Ok(v) => print!("{}", v),
          // normal message is just: The system cannot find the file specified
          Err(v) => Err(format!("{} {}", s, v))?
       }
       Ok(())
    }
    

提交回复
热议问题