arithmetic on const generics in rust

185 Views Asked by At

Consider the following two examples:

struct Polynomial<const DEGREE: usize> {
    factors: [isize; DEGREE + 1],
}

struct GenericSudoku<const SIZE: usize> {
    board: [[Option<usize>; SIZE.pow(2)]; SIZE.pow(2)],
}

These don't compile because of arithmetic operations on const generics (as decribed here).

It would however, be very convenient to have const generics that are derived from, but not equal to, other const generics.

Is there some other way to achieve this?

1

There are 1 best solutions below

1
On BEST ANSWER

You can do it on nightly, with #![feature(generic_const_exprs)], or if you feel brave, with typenum and generic-array:

use std::ops::{Add, Mul};

use generic_array::{ArrayLength, GenericArray};
use typenum::{op, U1};

struct Polynomial<Degree>
where
    Degree: Add<U1>,
    <Degree as Add<U1>>::Output: ArrayLength,
{
    factors: GenericArray<isize, op!(Degree + U1)>,
}

struct GenericSudoku<Size>
where
    Size: Mul,
    <Size as Mul>::Output: ArrayLength,
{
    board: GenericArray<GenericArray<Option<usize>, op!(sqr(Size))>, op!(sqr(Size))>,
}

type FourthDegreePolynomial = Polynomial<typenum::U4>;
type VeryLargeSudoku = GenericSudoku<typenum::U100>;

As you can see, it can get very unwieldy quickly.