Arithmetic on const generics?

pub struct Elev_Layer<const N: usize> {
    pub row_major_data: Vec<i16>,}

impl<const N: usize> Elev_Layer<N> {
    #[inline(always)]
    pub fn idx(y: usize, x: usize) -> usize {
        y * N + x}

    pub fn div_2(&self) -> Elev_Layer<N / 2> {
    }
}

For example, div_2 will do 512x512 -> 256x256; 256x256 -> 128x128, etc ...

Question: is it possible to do arithmetic (or even div by 2) on const generics ?

As the compiler error says, this is not currently possible in stable Rust:

error: generic parameters may not be used in const operations
  --> src/lib.rs:11:40
   |
11 |     pub fn div_2(&self) -> ElevLayer<{ N / 2 }> {
   |                                        ^ cannot perform const operation using `N`
   |
   = help: const parameters may only be used as standalone arguments, i.e. `N`

In nightly Rust, this can be done by enabling the generic_const_exprs feature, but it's still incomplete and often results in spurious compiler errors.

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.