我有一个String
newtype https://doc.rust-lang.org/rust-by-example/generics/new_types.html ErrorMessage
我用它来解决原型箱中的错误。 (我知道这是一个不好的做法。我将在发布之前构建一组适当的不同错误类型。)
I need ErrorMessage
实施Error https://doc.rust-lang.org/std/error/trait.Error.html特征,它(实际上)是空的,但要求它也实现Display https://doc.rust-lang.org/std/fmt/trait.Display.html and Debug https://doc.rust-lang.org/std/fmt/trait.Debug.html特征,我已经做到了。
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)
}
}
。然而,我最近遇到Deref https://doc.rust-lang.org/std/ops/trait.Deref.html并想知道它是否可以自动将特征实现委托给实现String
from self.0
.
impl std::ops::Deref for ErrorMessage {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
这允许我调用类似的方法.to_string()
on an ErrorMessage
, and 解除引用强制 https://doc.rust-lang.org/1.30.0/book/first-edition/deref-coercions.html会让它用我的Deref
实现自动查找fmt
and to_string
的实施self.0
/*self
.
然而,ErrorMessage
itself实际上不是Display
or Debug
。如果我尝试println!
or format!
直接实例我收到错误,并且.
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`
有什么办法可以使用吗Deref
, DerefMut
,或类似于允许取消引用的值满足原始值的特征边界的东西。我正在寻找自动的东西,作为手动编写的替代方案impl
块来委派每个人。