We have all seen how one can use the question mark operator to convert errors into Box<dyn Error>
, which especially useful for the main function:
fn main() -> Result<(), Box<dyn Error>> {
returns_error()?;
Ok(())
}
This works because there is an implementation of From<T: Error>
for Box<dyn Error>
(modulo lifetimes). Now I tried to do the same thing but just replacing Error
with Debug
.
fn main() -> Result<(), Box<dyn Debug>> {
returns_error()?;
Ok(())
}
(The idea just being that I don't want to implement Error
for all my custom error types, because I don't want to implement Display
, but Debug
can be easily derived and is enough for my error reporting purposes.)
Surprisingly, this does not work. It looks like there is no corresponding From implementation for Debug
, just for Error
. This confuses me, because I thought there was a blanket implementation for this for all traits. But it turns out there is just one manual implementation for Error
.
So my question is, why is there no blanket implementation of something like
impl<'a, T> From<T> for Box<dyn SomeTrait + 'a>
where
T: SomeTrait + 'a,
for all traits SomeTrait
? (Or maybe auto implementation would be a better term, as it's generic over all traits.)
(In fact I would expect this not just for Box but for all kind of pointers that can hold dyn SomeTrait
.)
This is especially annoying since the trait Termination
(which is basically what you want to return from the main function) is implemented for all Result<(), E: Debug>
(see here), but the above behavior basically means I can't really construct Result<(), E: Debug>
in a nice way. (Because I have different error types so I need to work with trait objects as the type E
, and then I lose the question mark operator as just explained.) And when I do the work and implement Error
for all error types, the implementation won't even get used because it just uses the Debug
functionality!