如何制作需要固定大小数组的特征绑定?

时间:2019-06-11 04:45:41

标签: arrays rust traits

我正在尝试创建仅由其他特征组成的特征,最终目标是创建一个证明类型是大小数组的特征。

此外,我希望能够在稳定的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寻找它们。

Playground

1 个答案:

答案 0 :(得分:2)

const泛型(夜间)

将来,您可以使用const泛型直接表达这一点:

#![feature(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(稳定)

我可能只会在稳定的Rust中使用AsRef<[T]>;对于您调用的所有功能(iterlenindex),您已经委派了一个分片:

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);
}