我可以使用 Deref<Target = Other> 从 Other 继承特征实现吗?

Can I use Deref<Target = Other> to inherit trait implementations from Other?

我有一个 String newtype ErrorMessage 用于原型板条箱中的错误。 (我知道这是一个不好的做法。我会在发布之前构建一组适当的不同错误类型。)

我需要 ErrorMessage 来实现 Error trait, which is (practically) empty but requires that it also implement the Display and Debug 特征,我已经做到了。

pub struct ErrorMessage(pub String);
impl std::error::Error for ErrorMessage {}
impl std::fmt::Display for ErrorMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
impl std::fmt::Debug for ErrorMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

This works fine. However, I recently came across Deref 并且想知道它是否可以自动将特征实现委托给 self.0String 的实现。

impl std::ops::Deref for ErrorMessage {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

这允许我在 ErrorMessage 上调用 .to_string() 等方法,deref coercion 将让它使用我的 Deref 实现自动找到 fmtto_stringself.0/*self.

上的实现

然而,ErrorMessage 本身 实际上并不是 DisplayDebug。如果我直接尝试 println!format! 一个实例,我会得到一个错误,并且 it doesn't satisfy the bounds for Error.

fn main() -> Result<(), ErrorMessage> {
    Err(ErrorMessage("hello world".to_string()))
}
error[E0277]: `ErrorMessage` doesn't implement `std::fmt::Display`
 --> src/main.rs:2:6
  |
2 | impl std::error::Error for ErrorMessage {}
  |      ^^^^^^^^^^^^^^^^^ `ErrorMessage` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `ErrorMessage`

有没有什么方法可以使用 DerefDerefMut 或类似的东西来允许解除引用的值满足原始值的特征边界。我正在寻找自动的东西,作为手动编写 impl 块来委托每个块的替代方法。

Is there any way to use Deref, DerefMut, or something similar to allow dereferenced values to satisfy trait bounds for the original values.

没有。取消引用内部类型的外部类型本身并不实现内部类型所具有的特征。

as an alternative to manually writing impl blocks to delegate each of them.

最好的办法可能是创建一个或多个宏。我个人对 first-class delegation support.

抱有希望