Using associated constants in traits - best practice

I want to define the following trait:

pub trait MyTrait {
    type T;
    const N: usize;

    fn compress(&self, input: [Self::T; Self::N]) -> Self::T;
}

But it doesn't work:

error: generic parameters may not be used in const operations
 --> src/main.rs:5:41
  |
5 |     fn compress(&self, input: [Self::T; Self::N]) -> Self::T;
  |                                         ^^^^^^^ cannot perform const operation using `Self`
  |
  = note: type parameters may not be used in const expressions

My understanding is that associated constants in traits are simply not strong enough yet.

Now my question: What's the best practice to still make this somehow work?

  • I've heard of the generic_array crate. But ideally I would like to avoid such non-orthodox constructions :confused:
  • Make const N: usize a generic instead of an associated type. (Then it works.)
  • Is the whole thing perhaps already possible with nightly features?
  • Any other suggestions?

Thank you!

the feature name is generic_const_exprs

1 Like

It depends on what you want to achieve. If you really want to keep it like this, with an associated constant, you should use the nightly feature generic_const_exprs, like in this playground.

However, if you prefer to avoid unstable features, you may want to use generic const, like here. The main difference between both - excepted the stability - is that using a generic will make possible to implement the trait multiple times for a same type, with different values of N, while when you put N an associated const, you have the guarantee to have only one implementation. (Same then for T.)

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.