rust - 为什么 "large"数组没有实现 std::fmt::Debug?

标签 rust

<分区>

我可以在 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.

关于rust - 为什么 "large"数组没有实现 std::fmt::Debug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41162696/

相关文章:

rust - 是否可以为 `time::Duration` 之类的结构指定全局常量?

rust - 如何通过匹配处理 Rust 中的多个可变借用?

unix - 如何从 Rust 写入特定的原始文件描述符?

rust - 我怎样才能检测到错误而不是让这个 Rust 程序中止?

oop - 为什么 Rust 不支持特征对象向上转换?

rust - 无法移出 `FnMut` 闭包中捕获的变量

rust - 用 Rust 解析二进制协议(protocol)的最佳方法是什么

generics - 无法访问动态特征实现中的结构字段

rust - 如何分配与高速缓存行的大小对齐的Vec <u8>?

rust - 哪里有课!红 bean 杉的宏