Using associated constants in traits - best practice

⚓ Rust    📅 2025-08-14    👤 surdeus    👁️ 2      

surdeus

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!

2 posts - 2 participants

Read full topic

🏷️ Rust_feed