我有 HashMap
的 typedef:
pub type Linear = HashMap<i16, f64>;
impl fmt::Debug for Linear {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// write!...
}
}
我想为它定制打印,但它不想编译。是否可以在不制作包装器的情况下覆盖它?
最佳答案
Is it possible to override it without making a wrapper?
不,您需要制作 wrapper 。请记住,类型别名不会创建新类型 — 这就是它们被称为别名 的原因。如果您能够在此处重新定义 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());
}
关于logging - 是否可以覆盖类型的现有 Debug 实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45883045/