gpt4 book ai didi

Rust 无法识别切片

转载 作者:行者123 更新时间:2023-11-29 08:23:14 25 4
gpt4 key购买 nike

<分区>

我有一个[u8; 128] 我想打印。为此,我使用调试格式将该缓冲区的借用传递给 println!。但是,我收到编译器错误。

编译器说 [u8;128] 没有实现 std::fmt::Debug。然而,我向 println! 传递了一个借用,这让我质疑为什么 Rust 不识别这是一个切片。我能够通过将 [#derive(Debug)] 附加到具有一个成员 buf: &[u8] 的结构来解决问题。通过此结构将我的缓冲区传递给 println! 解决了问题,这告诉我 &[u8] 确实实现了 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 链接:https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=b95ad4762f23ca35e890d0cbd2c072ce

我希望它编译得很好。但是,编译器提示 特性 std::fmt::Debug 没有为 [u8; 128],正如我之前所说。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com