【问题标题】:Why does println! work only for arrays with a length less than 33?为什么 println!仅适用于长度小于 33 的数组?
【发布时间】:2016-01-07 07:39:49
【问题描述】:

在 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 个元素的类型,但随后放弃了它的检测。或者为什么它不起作用?

【问题讨论】:

    标签: arrays rust println


    【解决方案1】:

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

    下面的旧答案供参考。


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

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

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

    顺便说一句:通常你可以通过简单的前缀&从数组中获取一个切片,但是println参数的工作方式有点不同,所以你需要添加全范围索引[..]


    这种情况未来可能会有所改善。 RFC 2000: Const Generics 已经被接受并且主要在编译器中实现。它将允许impl 块泛型超过数组的长度。您可以在the corresponding tracking issue 上跟踪实施和稳定的状态。

    【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    相关资源
    最近更新 更多