rust - 为什么特征类型 `Box<dyn Error>` 错误与 "Sized is not implemented"但 `async fn() -> Result<(), Box<dyn Error>>` 有效?

标签 rust

我有以下简化代码。

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
编译器抛出以下错误
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)>`
我不确定我是否正确理解了问题。
我正在使用 Box<dyn Error>因为我没有具体的类型并且装箱错误可以处理所有错误。在我的实现中 LocaSystemData , 我加了 <T as Metric>::Error: 'static (编译器给了我这个提示,而不是我的想法)。在我添加了 'static 之后要求编译器提示大小未知。发生这种情况是因为 'static 的大小类型应该在编译时总是已知的,因为静态的含义。
我改了Metric trait 以便我摆脱 type Error;现在我有以下异步特征函数并且我的代码可以编译
Playground
async fn refresh_metric(&mut self) -> Result<Self::Output, Box<dyn Error>>;
为什么我的第二个版本可以编译而第一个版本没有?对于我作为一个人来说,代码完全一样。我觉得我欺骗了编译器:-)。

最佳答案

错误消息有点误导,因为它代表了在类型约束解析期间出现的中间问题。同样的问题可以在没有异步的情况下重现。

use std::error::Error;

trait Metric {
    type Error: Error;
}

struct StaticMetric;

impl Metric for StaticMetric {
    type Error = Box<dyn Error>;
}
问题的根源在于 Box<dyn Error>不实现 std::error::Error .并按照 From<Box<E>> for Box<dyn Error> 的执行指定,内型E也必须是 Sized .
impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a>
因此,Box<dyn Error>不应分配给关联类型 Metric::Error .
除了完全摆脱关联类型之外,这可以通过引入您自己的新错误类型来解决,该类型可以流入主函数。
#[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
也可以看看:
  • How do you define custom `Error` types in Rust?
  • How can I implement From for both concrete Error types and Box<Error> in Rust?
  • 关于rust - 为什么特征类型 `Box<dyn Error>` 错误与 "Sized is not implemented"但 `async fn() -> Result<(), Box<dyn Error>>` 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62450500/

    相关文章:

    rust - 如何对枚举进行运算符重载?

    rust - 不同具体类型泛型的 Vec

    rust - Rust 中单位类型的用途是什么?

    rust - 为什么编译器声称来自更高级别特征绑定(bind)的关联类型没有实现 `Display` ,即使它应该实现?

    json - 如何将多个键值条目的 JSON 对象反序列化为 Rust 中的自定义结构

    module - 当有 main.rs 和 lib.rs 时 Rust 模块混淆

    rust - 我可以从单个字节 (u8) 创建可变切片 &mut [u8] 吗?

    rust - 比较切片和生命周期

    rust - 使用 thread::scoped 时代码未并行运行

    struct - 具有特征字段的结构,但可选