gpt4 book ai didi

arrays - 为什么 println!仅适用于长度小于 33 的数组?

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

在 Rust 中,这是可行的:

fn main() {
let a = [0; 32];
println!("{:?}", a);
}

但这不是:

fn main() {
let a = [0; 33];
println!("{:?}", a);
}

编译错误:

error[E0277]: the trait bound `[{integer}; 33]: std::fmt::Debug` is not satisfied
--> src/main.rs:3:22
|
3 | println!("{:?}", a);
| ^ the trait `std::fmt::Debug` is not implemented for `[{integer}; 33]`
|
= note: `[{integer}; 33]` cannot be formatted using `:?`; if it is defined in your crate, add `#[derive(Debug)]` or manually implement it
= note: required by `std::fmt::Debug::fmt`

我假设 std::fmt::Debug 函数以某种方式检测了最多 32 个元素长度的类型,但随后放弃了检测。或者为什么它不起作用?

最佳答案

从 Rust 1.47 (2020-10-08) 开始,this is no longer true ! 几乎所有特征现在都为任意长度的数组实现。所以您现在可以打印长度为 33 的数组!

下面的旧答案供引用。


遗憾的是,Rust 还不支持整数作为泛型参数。因此,为每个数组 [T; 实现一个特征(如 Debug)并不容易。 N]。目前,标准库使用一个宏来轻松实现所有长度不超过 32 的特征。

要输出数组,您可以通过这种方式轻松地将其转换为切片 (&[T]):

let a = [0; 33];
println!("{:?}", &a[..]);

顺便说一句:通常您可以通过简单地在 & 前加上前缀来从数组中获取切片,但是 println 参数的工作方式有点不同,因此您需要添加完整的范围索引 [..].


future 情况可能会有所改善。 RFC 2000: Const Generics已被接受并主要在编译器中实现。它将允许 impl block 在数组的长度上通用。您可以在 the corresponding tracking issue 上跟踪实现和稳定的状态。 .

关于arrays - 为什么 println!仅适用于长度小于 33 的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58859214/

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