我可以在 Debug
中打印以下数组:
fn main() {
let array = [0; 5];
println!("{:?}", array);
}
但是,如果大小更大,假设为 50,则默认不会实现 std::fmt::Debug
特性:
fn main() {
let array = [0; 50];
println!("{:?}", array);
}
编译错误:
error[E0277]: the trait bound [{integer}; 50]: std::fmt::Debug
is not satisfied
为什么 std::fmt::Debug
特性没有为某些大小的数组实现?
来自 https://doc.rust-lang.org/std/primitive.array.html :
Arrays of sizes from 0 to 32 (inclusive) implement the following
traits if the element type allows it:
- Clone (only if T: Copy)
- Debug
- IntoIterator (implemented for &[T; N] and &mut [T; N])
- PartialEq, PartialOrd, Eq, Ord
- Hash
- AsRef, AsMut
- Borrow, BorrowMut
- Default
This limitation on the size
N exists because Rust does not yet support code that is generic over
the size of an array type. [Foo; 3] and [Bar; 3] are instances of same
generic type [T; 3], but [Foo; 3] and [Foo; 5] are entirely different
types. As a stopgap, trait implementations are statically generated up
to size 32.
Arrays of any size are Copy if the element type is Copy. This works
because the Copy trait is specially known to the compiler.