Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a trait type `Box<dyn Error>` error with "Sized is not implemented" but `async fn() -> Result<(), Box<dyn Error>>` works?

Tags:

I’ve the following simplified code.

use async_trait::async_trait; // 0.1.36
use std::error::Error;

#[async_trait]
trait Metric: Send {
    type Output;
    type Error: Error;

    async fn refresh_metric(&mut self) -> Result<Self::Output, Self::Error>;
}

#[derive(Default)]
struct StaticMetric;

#[async_trait]
impl Metric for StaticMetric {
    type Output = ();
    type Error = Box<dyn Error>;

    async fn refresh_metric(&mut self) -> Result<Self::Output, Self::Error> {
        Ok(())
    }
}

struct LocalSystemData<T> {
    inner: T,
}

impl<T> LocalSystemData<T>
where
    T: Metric,
    <T as Metric>::Error: 'static,
{
    fn new(inner: T) -> LocalSystemData<T> {
        LocalSystemData { inner }
    }

    async fn refresh_all(&mut self) -> Result<(), Box<dyn Error>> {
        self.inner.refresh_metric().await?;
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let mut sys_data = LocalSystemData::new(StaticMetric::default());
    sys_data.refresh_all().await?;

    Ok(())
}

Playground

The compiler throws the following error

error[E0277]: the size for values of type `(dyn std::error::Error + 'static)` cannot be known at compilation time
  --> src/main.rs:18:18
   |
5  | trait Metric: Send {
   |       ------ required by a bound in this
6  |     type Output;
7  |     type Error: Error;
   |                 ----- required by this bound in `Metric`
...
18 |     type Error = Box<dyn Error>;
   |                  ^^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `(dyn std::error::Error + '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 because of the requirements on the impl of `std::error::Error` for `std::boxed::Box<(dyn std::error::Error + 'static)>`

I'm not really sure if I understand the problem correct.

I’m using Box<dyn Error> because I don’t have a concrete type and boxing an error can handle all errors. In my implementation of LocaSystemData, I added <T as Metric>::Error: 'static (the compiler gave me that hint, not my idea). After I added the 'static requirement the compiler complains about that the size is unknown. This happens because the size of a 'static type should always known at compile time because the implication of static.

I changed the Metric trait so that I get rid of the type Error; Now I've the following async trait function and my code compiles

Playground

async fn refresh_metric(&mut self) -> Result<Self::Output, Box<dyn Error>>;

Why does my second version compile and the first one does not? For me as a human the code does exactly the same. I feel I tricked the compiler :-).

like image 381
createproblem Avatar asked Jun 18 '20 12:06

createproblem


1 Answers

The error message is a bit misleading, as it represents an intermediate issue that emerged during type constraint resolution. The same problem can be reproduced without async.

use std::error::Error;

trait Metric {
    type Error: Error;
}

struct StaticMetric;

impl Metric for StaticMetric {
    type Error = Box<dyn Error>;
}

The root of the problem is that Box<dyn Error> does not implement std::error::Error. And as specified by the implementation of From<Box<E>> for Box<dyn Error>, the inner type E must also be Sized.

impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a>

Therefore, Box<dyn Error> should not be assigned to the associated type Metric::Error.

Other than getting rid of the associated type altogether, this can be fixed by introducing your own new error type which can flow into the main function.

#[derive(Debug, Default)]
struct MyErr;

impl std::fmt::Display for MyErr {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("I AM ERROR")
    }
}
impl Error for MyErr {}

#[async_trait]
impl Metric for StaticMetric {
    type Output = ();
    type Error = MyErr;

    async fn refresh_metric(&mut self) -> Result<Self::Output, Self::Error> {
        Ok(())
    }
}

Playground

See also:

  • How do you define custom `Error` types in Rust?
  • How can I implement From for both concrete Error types and Box<Error> in Rust?
like image 158
E_net4 stands with Ukraine Avatar answered Sep 30 '22 20:09

E_net4 stands with Ukraine