简体   繁体   English

为什么特征类型为`Box<dyn error> ` 错误“未实现大小”但 `async fn() -&gt; Result&lt;(), Box<dyn error> &gt;` 有效吗?</dyn></dyn>

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

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.我正在使用Box<dyn Error>因为我没有具体的类型,并且装箱错误可以处理所有错误。 In my implementation of LocaSystemData , I added <T as Metric>::Error: 'static (the compiler gave me that hint, not my idea).在我的LocaSystemData实现中,我添加了<T as Metric>::Error: 'static (编译器给了我这个提示,而不是我的想法)。 After I added the 'static requirement the compiler complains about that the size is unknown.在我添加'static要求后,编译器抱怨大小未知。 This happens because the size of a 'static type should always known at compile time because the implication of static.因为'static .

I changed the Metric trait so that I get rid of the type Error;我更改了Metric特征,以便摆脱type Error; Now I've the following async trait function and my code compiles现在我有以下异步特征 function 并且我的代码编译

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:-).我觉得我欺骗了编译器:-)。

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 .问题的根源在于Box<dyn Error>没有实现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 .并且正如Box<dyn Error>From<Box<E>>的实现所指定的,内部类型E也必须是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 .因此,不应将Box<dyn Error>分配给关联的类型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.除了完全摆脱关联类型之外,这可以通过引入您自己的新错误类型来解决,该错误类型可以流入主 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:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM