Generic parameter in const op w/o unstable

I want to do something like this:

pub trait Foo_T {
  const n: usize;

  pub fn write(..., data: &[u8; Self::n], ...) { ... }
}

but can not due to generic parameter in const op.

Without going to Rust unstable, is there a way to fake this ?

Here's one way.

// Optionally omit `T`
pub trait Array<T> {
    const N: usize;
    // ... all the things you want to do with arrays ...
}

impl<T, const N: usize> Array<T> for [T; N] {
    const N: usize = N;
}

pub trait FooT {
    type ByteArray: Array<u8>;

    fn write(&self, data: &Self::ByteArray) {}
}

There may be some more direct ways using some const-eval-panic hacks which are too far out of cache for me to recreate off the top of my head just now.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.