为大型数组类型实现调试特征 [英] Implement Debug trait for large array type

查看:35
本文介绍了为大型数组类型实现调试特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

收集 Rust 为数组大小提供了调试实现32 及更小.

我还收集我可以实现调试通过简单地使用带有很长格式说明符的 write! 来处理更大的数组.但我想知道是否有更好的方法.

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

解决方案

use std::fmt;结构体数组{数据:[T;1024]}implfmt::Debug for Array{fn fmt(&self, formatter: &mut fmt::Formatter) ->fmt::结果{self.data[..].fmt(格式化程序)}}fn 主(){让数组 = 数组 { 数据:[0u8;第1024话println!("{:?}", 数组);}

无法为 [T; 实现调试;1024] 或某个具体类型的数组(即 [u8; 1024].从其他 crate 中为来自其他 crate 的类型实现 trait,或从另一个 crate 为泛型类型实现 trait,都是设计不允许的,

I gather that Rust provides Debug impl's for arrays size 32 and smaller.

I also gather that I could implement Debug on a larger array by simply using write! with a very long format specifier. But I'm wondering if there's a better way.

What is the recommended method for implementing Debug for an array of length, say, 1024?

解决方案

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);
}

It's not possible to implement Debug for [T; 1024] or some array of a concrete type (ie. [u8; 1024]. Implementing traits from other crates for types from other crates, or implementing a trait from another crate for a generic type, are both not allowed by design,

这篇关于为大型数组类型实现调试特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆