我有一个String NEWTYPE ErrorMessage,我使用了一个原型箱错误。(我知道这是一种不好的做法。我将在发布之前构建一组适当的不同错误类型。)
我需要ErrorMessage实现Errortrait,它(实际上)是空的,但要求它还实现Display和Debugtrait,我已经完成了。
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)
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常。但是,我最近遇到Deref并想知道它是否可以自动将 trait 实现委托给Stringfrom的实现self.0。
impl std::ops::Deref for ErrorMessage {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
Run Code Online (Sandbox Code Playgroud)
这允许我调用类似.to_string()on an 的方法ErrorMessage,并且deref coercion将让它使用我的Deref实现来自动查找/上的fmt和to_string实现。self.0*self
但是,ErrorMessage 它本身实际上不是Display或Debug. 如果我直接尝试println!或format!实例,我会收到一个错误,并且它不满足Error.
fn main() -> Result<(), ErrorMessage> {
Err(ErrorMessage("hello world".to_string()))
}
Run Code Online (Sandbox Code Playgroud)
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`
Run Code Online (Sandbox Code Playgroud)
有什么方法可以使用Deref、DerefMut或类似的东西来允许取消引用的值满足原始值的特征边界。我正在寻找一些自动的东西,作为手动编写impl块来委托每个块的替代方法。
| 归档时间: |
|
| 查看次数: |
492 次 |
| 最近记录: |