为什么特征类型“Box<dyn Error>"会出现“Sized is not implementation"的错误?但是`async fn() ->结果<(), Box<dyn Error>>`有效吗? [英] Why does a trait type `Box<dyn Error>` error with "Sized is not implemented" but `async fn() -> Result<(), Box<dyn Error>>` works?
问题描述
我有以下简化代码.
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(())
}
编译器抛出以下错误
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.
我使用 Box
因为我没有一个具体的类型并且装箱一个错误可以处理所有的错误.在我的 LocaSystemData
实现中,我添加了
(编译器给了我这个提示,不是我的想法).添加 'static
要求后,编译器抱怨大小未知.发生这种情况是因为 'static
类型的大小在编译时应该总是已知的,因为静态的含义.
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.
我更改了 Metric
trait 以便摆脱 type Error;
现在我有以下异步 trait 函数并且我的代码编译
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
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>;
}
问题的根源在于Box
没有实现std::error::Error
.并按照 From
对于Box
,内部类型E
也必须是大小
.
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>
因此,Box
不应分配给关联类型 Metric::Error
.
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(())
}
}
另见:
这篇关于为什么特征类型“Box<dyn Error>"会出现“Sized is not implementation"的错误?但是`async fn() ->结果<(), Box<dyn Error>>`有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!