[英]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.