rust - 如何忽略 `#[derive(Debug)]` 的通用参数?

标签 rust macros traits substrate derived

这是一个最小的 example代表我遇到的问题类型。

use core::fmt::Debug;

pub trait Config {
    type A: Debug;
}

#[derive(Debug)]
pub struct Info<T: Config> {
    pub field: T::A,
}

pub struct Conf;

impl Config for Conf {
    type A = i128;
}

fn main() {
    let s = Info::<Conf> {
        field: 123
    };
    dbg!(s);
}

我正在使用的框架 ( Substrate ) 使用了 Config 的概念聚合模块(托盘)的所有泛型类型的特征。

问题是试图#[derive(Debug)]对于仅使用对象关联类型的结构 T实现 Config仍然需要 T工具 Debug本身。

error[E0277]: `Conf` doesn't implement `Debug`
  --> src/main.rs:22:5
   |
22 |     dbg!(s);
   |     ^^^^^^^ `Conf` cannot be formatted using `{:?}`
   |
   = help: the trait `Debug` is not implemented for `Conf`
   = note: add `#[derive(Debug)]` to `Conf` or manually `impl Debug for Conf`

此外,我无法控制 Conf 的执行目的。无论如何,我不想打印任何关于 Conf 的信息对象本身。

有没有办法让#[derive(Debug)]对于 Info忽略 T

最佳答案

不幸的是,不是今天。您必须手动实现 Debug:

impl<T: Config> fmt::Debug for Info<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Info").field("field", &self.field).finish()
    }
}

有一个目的是让创建所谓的“完美派生”成为可能:根据需要而不是通用参数派生边界。参见示例 this lang team design meeting proposal .但是现在什么都没有。

关于rust - 如何忽略 `#[derive(Debug)]` 的通用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72392583/

相关文章:

haskell - 如何获取 TemplateHaskell 命名变量的文字值

rust - #[inline] 可以同时用于 trait 方法声明和实现吗?

Scala:让特质依赖于其他特质

rust - 无法推断返回包含引用的盒装特征的闭包的生命周期

c++ - 编译器中的哪个程序负责预处理器?

rust - wgpu 计算直接写入表面纹理 View

c - 在 visual studio 中调试宏时出现问题

c++ - boost add_reference 不适用于模板参数

unicode - 这个混合字符串如何在 unicode 单词边界上拆分

rust - 直接调用函数时,可变引用的生命周期足够长,但通过中间函数调用时,可变引用的生命周期不够长