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

标签 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!...
    }
}

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

最佳答案

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/

相关文章:

java - 如何向 Log4j 注册额外的 PropertySource?

logging - 企业库6 LogCallHandler抛出异常 "The LogWriter has not been set for the Logger static class"

string - 如何在 Rust 中获得 float 的紧凑但无损的字符串表示?

match - 由于无法访问模式,Rust 匹配失败

build - 如何从构建脚本 (build.rs) 访问当前的 cargo 配置文件(调试/发布,...)

java - SpringBoot 测试模块不在正确的类路径中搜索 log4j2 配置

具有多个模块的Python记录器

rust - 为什么 Vec 不实现 Iterator 特性?

logging - 日志语句阻止重构 : how to help this?

memory-management - 如何检测某个类型何时需要调用 'drop'?