48 个版本 (3 个稳定版)
1.1.0 | 2024 年 7 月 5 日 |
---|---|
1.0.0 | 2023 年 9 月 13 日 |
1.0.0-alpha.1 |
|
0.14.7 | 2023 年 3 月 28 日 |
0.0.3 | 2015 年 11 月 1 日 |
#24 in 数据结构
8,094,319 每月下载量
被 24,769 个包使用 (392 个直接使用)
105KB
2K SLoC
generic-array
该包实现了一个可以用于泛型数组类型的结构。
**需要最低 Rust 版本为 1.65.0
在 GH Pages 上的文档可能需要查看某些在 foreign crates 上的类型。
用法
Rust 1.51 之前,数组 [T; N]
在泛型方面存在问题,即它们无法根据长度 N
进行泛型化,因此这不会工作
struct Foo<N> {
data: [i32; N],
}
自 1.51 以来,下面的语法是有效的
struct Foo<const N: usize> {
data: [i32; N],
}
然而,截至本文撰写时,我们拥有的 const-generics 仍然是最低可行产品 (min_const_generics
),因此许多情况仍然会导致错误,例如以下示例
trait Bar {
const LEN: usize;
// Error: cannot perform const operation using `Self`
fn bar(&self) -> Foo<{ Self::LEN }>;
}
generic-array 定义了一个新的特质 ArrayLength
和一个结构体 GenericArray<T, N: ArrayLength>
,这使得上述实现成为可能
struct Foo<N: ArrayLength> {
data: GenericArray<i32, N>
}
trait Bar {
type LEN: ArrayLength;
fn bar(&self) -> Foo<Self::LEN>;
}
ArrayLength
特质由来自 typenum 包的 无符号整数类型 实现。例如,GenericArray<T, U5>
将几乎像 [T; 5]
一样工作
use generic_array::typenum::U5;
struct Foo<T, N: ArrayLength> {
data: GenericArray<T, N>
}
let foo = Foo::<i32, U5> { data: GenericArray::default() };
提供了 arr!
宏,以便更轻松地创建字面量数组,如下所示
let array = arr![1, 2, 3];
// array: GenericArray<i32, typenum::U3>
assert_eq!(array[2], 3);
功能标志
[dependencies.generic-array]
features = [
"more_lengths", # Expands From/Into implementation for more array lengths
"serde", # Serialize/Deserialize implementation
"zeroize", # Zeroize implementation for setting array elements to zero
"const-default", # Compile-time const default value support via trait
"alloc", # Enables From/TryFrom implementations between GenericArray and Vec<T>/Box<[T]>
"faster-hex" # Enables internal use of the `faster-hex` crate for faster hex encoding via SIMD
]
依赖项
~120–340KB