在“锈病”中,这起作用是:
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个元素的类型,但随后删除了它的检测。或者为什么不起作用?
发布于 2015-10-09 03:33:05
从锈蚀1.47 (2020-10-08)开始,这不再是真的了!几乎所有的性状都被实现为任意长度的数组。所以,您现在可以打印33长度的数组了!
下面的旧答案可供参考。
遗憾的是,Rust还不支持作为泛型参数的整数。因此,要为每个数组Debug
实现一个特性(如[T; N]
)并不容易。目前,标准库使用宏来轻松地实现所有长度最多为32的特征。
要输出数组,可以通过以下方式轻松地将其转换为片(&[T]
):
let a = [0; 33];
println!("{:?}", &a[..]);
顺便说一句:通常您可以通过简单的前缀&
从数组中获得一个片段,但是println
参数的工作方式有点不同,所以您需要添加完整的范围索引[..]
。
这种情况今后可能会有所改善。RFC 2000: Const Generics已经被接受,并且大部分在编译器中实现。它允许impl
块泛型于数组的长度。您可以跟踪相应的跟踪问题上的实现和稳定状态。
https://stackoverflow.com/questions/33036859
复制