I have a [u8; 128]
that I would like to print. To do so, I am passing in a borrow of that buffer to println!
using debug formatting. However, I am receiving a compiler error.
The compiler says that [u8;128]
does not implement std::fmt::Debug
. However, I am passing in a borrow to println!
, which leads me to question why Rust does not recognize this is a slice. I was able to fix the problem by attaching [#derive(Debug)]
to a struct with one member, buf: &[u8]
. Passing my buffer in through this struct to println!
solves the problem, which tells me that &[u8]
does indeed implement std::fmt::Debug
.
use std::io::prelude::*;
use std::net::TcpStream;
#[derive(Debug)]
struct Fah<'a> {
buf: &'a[u8],
}
fn main() -> std::io::Result<()> {
let mut stream = TcpStream::connect("216.58.194.206:80")?;
stream.write(&[1])?;
let mut buf = [0; 128];
stream.read(&mut buf)?;
println!("buf: {:?}", &buf); // This line does not compile
println!("fah: {:?}", Fah { buf: &buf}); // This line works fine
Ok(())
}
Playground link: https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=b95ad4762f23ca35e890d0cbd2c072ce
I expect this to compile just fine. However, the compiler complains that the trait std::fmt::Debug is not implemented for [u8; 128]
, as I said before.