1

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?

Mysquff
  • 293
  • 4
  • 11
  • 2
    first look how to return a dyn type in ANY normal function, main doesn't differs https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=220a415817a1bb756c99ef409c0ec02f – Stargateur Jan 30 '20 at 22:05
  • Thank you. To be fair, I have tried appending `.map_err(|e| Box::new(e))` to function calls, but it didn't work without casting with `as _` and resulted in the following error: `the trait std::convert::From> is not implemented for std::boxed::Box`. – Mysquff Jan 30 '20 at 22:17
  • 1
    + https://stackoverflow.com/questions/30661046/how-do-i-return-an-instance-of-a-trait-from-a-method – Stargateur Jan 30 '20 at 22:20

0 Answers0