簡體   English   中英

如何忽略`#[derive(Debug)]`的通用參數?

[英]How to ignore generic argument for `#[derive(Debug)]`?

這是一個代表我遇到的問題類型的最小示例

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特征的這個概念,它聚合了模塊 (pallet) 的所有泛型類型。

問題是嘗試#[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)] for Info ignore 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()
    }
}

有一個意圖是使創建所謂的“完美派生”成為可能:根據需要而不是通用參數派生界限。 例如參見這個 lang 團隊設計會議提案 但目前什么都沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM