Search code examples
genericsrust

How can I use types with size known at compile time as array length using struct generics in rust


How can I use generics with size that is known in compile time (are Sized) as struct array length based on their size

I have the following error:

error: generic parameters may not be used in const operations
 --> src/lib.rs:4:43
  |
4 |     arr: [Key; 1024 / std::mem::size_of::<Key>()]
  |                                           ^^^ cannot perform const operation using `Key`
  |
  = note: type parameters may not be used in const expressions

for the following code

Rust Playground

type SomeKey = u64;

// This does not work
struct NotWorking<Key: Sized> {
    arr: [Key; 1024 / std::mem::size_of::<Key>()]
}

struct Working {
    arr: [SomeKey; 1024 / std::mem::size_of::<SomeKey>()]
}


Solution

  • You currently can't on stable, it requires #![feature(generic_const_exprs)] and thus nightly:

    #![feature(generic_const_exprs)]
    struct NotWorking<Key>
    where
        // this where clause is required to constrain the generic, once GCEs
        // are complete its need might go away.
        [(); 1024 / std::mem::size_of::<Key>()]:,
    {
        arr: [Key; 1024 / std::mem::size_of::<Key>()],
    }