是否可以覆盖类型的现有Debug实现?

时间:2017-08-25 13:57:11

标签: logging rust

我有HashMap的typedef:

pub type Linear = HashMap<i16, f64>;

impl fmt::Debug for Linear {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
      // write!...
    }
}

我想要自定义打印,但它不想编译。是否可以在不制作包装的情况下覆盖它?

1 个答案:

答案 0 :(得分:8)

  

是否可以在不制作包装的情况下覆盖它?

不,你需要制作包装器。请记住类型别名不创建新类型 - 这就是为什么它们被称为别名。如果您能够在此处重新定义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());
}
相关问题