I have recently discovered that:
In Rust 2018 you can instead let your
#[test]s andmainfunctions return aResult: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, thenmainwill exit with an error code (not 0) and print out aDebugrepresentation oferr.
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?