2016-12-15 20 views
3

我可以在Debug打印以下陣列:爲什麼「大」數組不能實現std :: fmt :: Debug?

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

編譯錯誤:

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

然而,如果尺寸再大,我們說這是50,性狀std::fmt::Debug不會被默認實施:

error[E0277]: the trait bound [{integer}; 50]: std::fmt::Debug is not satisfied

爲什麼std::fmt::Debug特質不是陣列的某些尺寸來實現?

+0

作爲臨時解決辦法,則可以使用'&[T]'代替,因爲它是長度無關。 – aochagavia

回答

4

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.

+2

我希望2017年將是Rust得到整體通用參數的一年(如果它不僅僅是積分,我真的很喜歡它,但積分已經非常有用)。 –

相關問題