是否可以重写某个类型的现有Debug实现?
问题描述:
我曾经的typedef一个HashMap
:是否可以重写某个类型的现有Debug实现?
pub type Linear = HashMap<i16, f64>;
impl fmt::Debug for Linear {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// write!...
}
}
我想为它定制印刷,但并不希望编译。有没有可能覆盖它而不包装?
答
是否有可能重写它而不包装?
不,您需要制作包装。请记住,类型别名不会创建新类型 - 这就是为什么他们被称为别名。如果你能够在这里重新定义Debug
,你会影响每HashMap
(不是一个好主意)。
打印时只需要包装,因此您可以有println!("{:?}", DebugWrapper(&a_linear_value))
。
你可能是非常看中并提出延期性状做同样的事情:
use std::collections::HashMap;
use std::fmt;
pub type Linear = HashMap<i16, f64>;
trait MyDebug<'a> {
type Debug: 'a;
fn my_debug(self) -> Self::Debug;
}
impl<'a> MyDebug<'a> for &'a Linear {
type Debug = LinearDebug<'a>;
fn my_debug(self) -> Self::Debug { LinearDebug(self) }
}
struct LinearDebug<'a>(&'a Linear);
impl<'a> fmt::Debug for LinearDebug<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "custom")
}
}
fn main() {
let l = Linear::new();
println!("{:?}", l);
println!("{:?}", l.my_debug());
}