fizyk20 / generic-array

Generic array types in Rust
MIT License
404 stars 77 forks source link

How to instantiate a non-standard size generic-array #146

Closed eschorn1 closed 11 months ago

eschorn1 commented 11 months ago

After studying the documentation and code, it remains unclear to me how to instantiate a non-standard size array (such as 12345 below). I suspect it may not be doable at this point, but wanted to ask directly.

struct Foo<T, N: ArrayLength> {
    data: GenericArray<T, N>
}

let foo = Foo::<i32, U12345> { data: GenericArray::default() };

Thank you!

novacrazy commented 11 months ago

If by non-standard you mean a constant value not already provided in the typenum crate, then you'll have to define it yourself:

use generic_array::{typenum::*, ArrayLength, GenericArray};

struct Foo<T, N: ArrayLength> {
    data: GenericArray<T, N>,
}

// https://docs.rs/typenum/latest/typenum/operator_aliases/type.Prod.html
type U12345 = Prod<U15, U823>;

let foo = Foo::<i32, U12345> {
    data: GenericArray::default(),
};

Though do be aware that very large arrays have the potential to overflow the stack when creating them. That's not exactly a generic-array issue, just how Rust handles things, but can be made worse in debug builds.

eschorn1 commented 11 months ago

Ah, excellent, thanks! ( I thought I had tried this ; ) much appreciated.