我有一个typedef HashMap:
pub type Linear = HashMap<i16, f64>;
impl fmt::Debug for Linear {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// write!...
}
}
Run Code Online (Sandbox Code Playgroud)
我想为它自定义打印,但它不想编译.是否可以在不制作包装的情况下覆盖它?
是否可以在不制作包装的情况下覆盖它?
不,你需要制作包装.请记住,类型别名不会创建新类型 - 这就是它们被称为别名的原因.如果你能够在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());
}
Run Code Online (Sandbox Code Playgroud)