Is it possible for main function to return any kind of error that implements Debug trait?

40 views Asked by At

I have recently discovered that:

In Rust 2018 you can instead let your #[test]s and main functions return a Result:

use std::fs::File;

fn main() -> Result<(), std::io::Error> {
    let f = File::open("bar.txt")?;
    Ok(())
}

In this case, if say the file doesn't exist and there is an Err(err) somewhere, then main will exit with an error code (not 0) and print out a Debug representation of err.

Source: https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/question-mark-in-main-and-tests.html

However, what return type should I specify if there is more than one type of error returned in my main function? Since an error is used just to print out its Debug representation, I thought that it may be possible to return Result<(), dyn Debug>. Unfortunately, the code below:

use std::fmt::Debug;

#[derive(Debug)]
struct Error1;

#[derive(Debug)]
struct Error2;

fn do_something() -> Result<(), Error1> {}
fn do_something_else() -> Result<(), Error2> {}

fn main() -> Result<(), dyn Debug> {
    do_something()?;
    do_something_else()?;
    Ok(())
}

results in the following compilation error:

36 | / fn main() -> Result<(), dyn Debug> {
37 | |     do_something()?;
38 | |     do_something_else()?;
39 | |     Ok(())
40 | | }
   | |_^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `(dyn std::fmt::Debug + 'static)`
   = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
   = note: required by `std::result::Result`

Is there any workaround here? Or is the only solution to map all the function calls to one kind kind of error?

0

There are 0 answers