Using a const Associated Type in trait function signature

I have been trying to figure out how to specify the a function in a trait where the return type depends on an associated type. Specifically, for a const associated type.

pub trait FancyArray {
    const Length: usize;

    fn pad(&self) -> [u32; Self::Length] {
        [0; Self::Length]

However this code does not compile with this error:

❯ cargo check
    Checking category_theory_rust v0.1.0 (/Users/oliver/code/category_theory_rust)
error: generic parameters may not be used in const operations
 --> src/
3 |     fn pad(&self) -> [u32; Self::Length] {
  |                            ^^^^^^^^^^^^ cannot perform const operation using `Self`
  = note: type parameters may not be used in const expressions

error: constant expression depends on a generic parameter
 --> src/
4 |         [0; Self::Length]
  |             ^^^^^^^^^^^^
  = note: this may fail depending on what value the parameter takes

This seems really odd, since Self::Length is specified at compile time, so it feels like this should be possible. Could anyone tell me where to find out why this does not work?

You can do it on nightly with the generic_const_exprs feature (see issue)

Thanks! Adding #![feature(generic_const_exprs)] to the src/ solved this issue!

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.