为什么println!仅适用于长度小于33的数组? [英] Why does println! work only for arrays with a length less than 33?

查看:94
本文介绍了为什么println!仅适用于长度小于33的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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还不支持将整数用作通用参数.因此,要为每个数组[T; N]实现一个特征(如Debug)并不容易.当前,标准库使用宏轻松实现32位以内的所有特征.

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

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

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


这种情况将来可能会改善. RFC 2000:Const Generics 具有已经被接受并且主要在编译器中实现.这将允许在整个数组长度上通用的impl块.您可以在相应的跟踪问题上跟踪实施和稳定状态./p>

In Rust, this works:

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

but this doesn't:

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

Compile error:

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`

I assume that the std::fmt::Debug function somehow detects types up to a length of 32 elements, but then drops it's detection. Or why doesn't it work?

解决方案

Sadly, Rust does not support integers as generic parameters yet. Therefore it's not easy to implement a trait (like Debug) for every array [T; N]. Currently, the standard library uses a macro to easily implement the trait for all length up to 32.

To output the array, you can easily convert it to a slice (&[T]) this way:

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

By the way: Normally you can obtain a slice from an array by simply prefixing &, but println arguments work a bit different, so you need to add the full range index [..].


The situation is likely to improve in the future. RFC 2000: Const Generics has already been accepted and mostly implemented in the compiler. It would allow for impl blocks generic over the length of the array. You can track the status of implementation and stabilization on the corresponding tracking issue.

这篇关于为什么println!仅适用于长度小于33的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆