1 个不稳定发布
0.1.0 | 2023年11月14日 |
---|
#13 在 #zero-dependency
5KB
Dispair
Dispair (Disp-Err) 是一个零依赖(除 std
之外)的库,它提供了一个简单的包装结构体,为实现了 Debug
和 Display
的任何类型实现了 Error
。
示例
use dispair::Dispair;
use std::error::Error;
#[derive(Debug)]
struct TestStruct;
impl core::fmt::Display for TestStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
core::fmt::Debug::fmt(&self, f)
}
}
fn main() {
// Wrap `TestStruct` (which doesn't implement `Error`) in `Dispair` and return it.
let err = Dispair(TestStruct);
// Display just passes through to the wrapped value
assert_eq!(format!("{}", err), "TestStruct");
// Debug, however, does show `Dispair`.
assert_eq!(format!("{:?}", err), "Dispair(TestStruct)");
// We should be able to convert it into a `Box<dyn Error>`
let err_boxed: Box<dyn Error> = Box::new(err);
// And this should print nicely
assert_eq!(err_boxed.to_string(), "TestStruct");
}