13

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?

user12341234
  • 6,573
  • 6
  • 23
  • 48
  • I'd say that depends entirely on your use case. I've had cases where I needed to see every last value of my data. Sometimes, it's enough to write out some statistics about the data. It's your data, after all. – llogiq Jun 17 '15 at 21:05
  • Good point. And while I wait for an answer, I'm doing just that, printing a few important bits of information. But I'm still curious if there's a good way to print the entire array. – user12341234 Jun 17 '15 at 21:09
  • 3
    you don't need a very long format -- any array is printable as a slice. – bluss Jun 17 '15 at 21:53

1 Answers1

22
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,

A.B.
  • 15,364
  • 3
  • 61
  • 64
  • Interesting design choice, is the rational documented anywhere? Anyway, thanks for the answer, it's certainly acceptable given the circumstance. – user12341234 Jun 18 '15 at 01:18
  • 6
    @user12341234: This is known as "coherence rules", and the rationale is to guarantee that when use the impl of `Trait` for `Struct` you are guaranteed to always have the same behavior regardless of which modules/crates you are linked with, because anything else is surprising. There have been various proposals to relax those rules in some ways, but the Rust team is very attentive to avoid footguns. – Matthieu M. Jun 18 '15 at 06:07