为大型数组类型实现Debug trait

use*_*234 9 traits rust

收集 Rust为大小为32或更小的数组提供Debug impl.

我还收集,我可以简单地使用较大的阵列上实现调试write!一个很长的格式说明.但我想知道是否有更好的方法.

为长度数组(例如1024)实现Debug的推荐方法是什么?

A.B*_*.B. 14

use std::fmt;

struct Array<T> {
    data: [T; 1024]
}

impl<T: fmt::Debug> fmt::Debug for Array<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        self.data[..].fmt(formatter)
    }
}

fn main() {
    let array = Array { data: [0u8; 1024] };

    println!("{:?}", array);
}
Run Code Online (Sandbox Code Playgroud)

不能为[T;实现Debug].1024]或某些具体类型的数组(即.[u8; 1024].从其他包装箱中为其他包装箱中的类型实施特征,或从另一个包装箱中为特定类型实施特征,均不被设计,

  • @ user12341234:这被称为"一致性规则",其基本原理是保证当使用`Trait`的impl为`Struct`时,无论你链接到哪个模块/ crate,都可以保证始终具有相同的行为. ,因为其他任何事情都令人惊讶.在某些方面有各种各样的建议来放宽这些规则,但Rust团队非常注意避免使用脚趾. (5认同)