Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to use an associated constant in an associated type in Rust

I want to create a trait to define a constant LEN and an array of length LEN as the output type of a trait function, but I am not allowed to:

trait TransformIntoArray {
    const LEN: usize;
    fn transform_into_array(&self) -> [f64; Self::LEN];
    fn array_description(&self) -> [&'static str; Self::LEN];
}

this does not work. I want to make both return-types of the two function have the same length that is defined in the trait implementation. But that's not possible here.

Is there another solution I don't see?

like image 910
exocortex Avatar asked Aug 31 '25 03:08

exocortex


2 Answers

The other answers do a good job working around the limitations of stable Rust. On nightly Rust, there is an feature that allows your original code to compile:

#![allow(incomplete_features)]
#![feature(generic_const_exprs)]

trait TransformIntoArray {
   const LEN: usize;
   fn transform_into_array(&self) -> [f64; Self::LEN];
   fn array_description(&self) -> [&'static str; Self::LEN];
}

The feature is deemed incomplete, but is complete enough for the above to work. Only use this as a last resort, if the stable workarounds don't work.

like image 183
Finn Bear Avatar answered Sep 02 '25 18:09

Finn Bear


You could use the constant as generic parameter:

trait TransformIntoArray<const LEN: usize> {
    fn transform_into_array(&self) -> [f64; LEN];
    fn array_description(&self) -> [&'static str; LEN];
}
like image 40
Matthias Avatar answered Sep 02 '25 18:09

Matthias