这是一个最小的 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/