Skip to content

Consider relaxing the Sized requirement in impl Error for Box<T> #104485

Open
@Veetaha

Description

@Veetaha

As for today the following blanket implementation exists:

#[stable(feature = "box_error", since = "1.8.0")]
impl<T: core::error::Error> core::error::Error for Box<T> {
#[allow(deprecated, deprecated_in_future)]
fn description(&self) -> &str {
core::error::Error::description(&**self)
}
#[allow(deprecated)]
fn cause(&self) -> Option<&dyn core::error::Error> {
core::error::Error::cause(&**self)
}
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
core::error::Error::source(&**self)
}
}

The problem with this is that T is required to be Sized, so, for example, Box<dyn Error> doesn't implement Error. It looks like a straightforward and intuitive assumption that Box<dyn Error> should implement Error trait, but it doesn't.

Going even further, there is an inconsistency between the blanket impls for Arc as well, because there exists an analogous impl for Arc that has relaxed Sized? requirement:

rust/library/alloc/src/sync.rs

Lines 2769 to 2788 in e702534

#[stable(feature = "arc_error", since = "1.52.0")]
impl<T: core::error::Error + ?Sized> core::error::Error for Arc<T> {
#[allow(deprecated, deprecated_in_future)]
fn description(&self) -> &str {
core::error::Error::description(&**self)
}
#[allow(deprecated)]
fn cause(&self) -> Option<&dyn core::error::Error> {
core::error::Error::cause(&**self)
}
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
core::error::Error::source(&**self)
}
fn provide<'a>(&'a self, req: &mut core::any::Demand<'a>) {
core::error::Error::provide(&**self, req);
}
}

Use Case

The use case where I stumbled with this problem is where I wanted to put Box<dyn Error> as a source error in thiserror error enum, but I couldn't because that type doesn't implement Error trait.

Workarounds

The workaround for this problem is to use Arc<T> instead of Box<T> when an Error impl is required for Sized? type. It's also possible to convert Box<dyn Error> into an Arc<dyn Error> via this From impl.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions