Implement Debug trait for large array type

后端 未结 1 1981
感动是毒
感动是毒 2021-01-17 11:42

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!

相关标签:
1条回答
  • 2021-01-17 12:23
    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,

    0 讨论(0)
提交回复
热议问题