我正在尝试创建一个特征,它只是其他特征的组合,最终目标是创建一个特征来证明该类型是一个大小数组。
此外,我希望能够在没有额外库的情况下在稳定的 Rust 中执行此操作。
我已经尝试添加一堆特征边界来模拟固定大小数组的限制,如下所示:
trait SizedArray<T>
where
T: Sized + Eq + Copy + Clone,
{
}
impl<T> SizedArray<T> for [T; 32] where T: Sized + Eq + Copy + Clone {}
fn processArray<T, U>(array: T)
where
T: SizedArray<U>,
U: Sized + Eq + Copy + Clone,
{
let a = array[0];
for i in array.iter() {
let size = array.len();
/* do something with the array */
}
}
fn main() {
let array = [0u8; 32];
processArray(array);
}
但是当我这样做并尝试使用固定大小的数组时,例如 [u8; 32]
:
我得到:
Compiling playground v0.0.1 (/playground)
error[E0608]: cannot index into a value of type `T`
--> src/main.rs:12:13
|
12 | let a = array[0];
| ^^^^^^^^
error[E0599]: no method named `iter` found for type `T` in the current scope
--> src/main.rs:13:20
|
13 | for i in array.iter() {
| ^^^^
error[E0599]: no method named `len` found for type `T` in the current scope
--> src/main.rs:14:26
|
14 | let size = array.len();
| ^^^
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `len`, perhaps you need to implement it:
candidate #1: `std::iter::ExactSizeIterator`
类型[u8; 32]
显然有所有这些方法,但我不知道如何告诉 Rust 去寻找它们。
最佳答案
Const 泛型(每晚)
以后可以直接用const泛型来表达:
#![feature(min_const_generics)]
fn process_array<T, const N: usize>(array: [T; N])
where
T: Sized + Eq + Copy + Clone,
{
let a = array[0];
for i in array.iter() {
let size = array.len();
/* do something with the array */
}
}
fn main() {
let array = [0u8; 32];
process_array(array);
}
另见:
AsRef(稳定)
我可能只使用 AsRef<[T]>
在稳定的 Rust 中;对于您调用的所有函数( iter
、 len
、 index
),无论如何您已经委托(delegate)给了一个切片:
fn process_array<T>(array: impl AsRef<[T]>)
where
T: Sized + Eq + Copy + Clone,
{
let array = array.as_ref();
let _a = array[0];
for _i in array.iter() {
let _size = array.len();
/* do something with the array */
}
}
fn main() {
let array = [0u8; 32];
process_array(array);
}
关于arrays - 如何创建需要固定大小数组的特征边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56536618/