how to define a family of structs with different const parameters in rust?

The unstable language feature, min_const_generics is quite limited in what it lets you do. As you discovered, you can’t use expressions involving generic constants in type arguments.

However, in stable Rust, you can use the typenum crate, which works in a similar way to what you were trying, but does all of the type-level boilerplate for you.

use std::ops::Sub;
use typenum::{Unsigned, U1, U2, U3}; // 1.12.0

struct Level<N: Unsigned>(N);

impl<N: Unsigned> Level<N> {
    fn value() -> usize {
        N::to_usize()
    }
}

trait HierarchicalLevel {
    type NextLevel;
}

impl<N> HierarchicalLevel for Level<N>
where
    N: Sub<U1> + Unsigned,
    <N as Sub<U1>>::Output: Unsigned,
{
    type NextLevel = Level<<N as Sub<U1>>::Output>;
}

fn main() {
    assert_eq!(
        <Level::<U3> as HierarchicalLevel>::NextLevel::value(),
        Level::<U2>::value()
    );
}

The types U0, U1, U2,… represent the unsigned integers 0, 1, 2,…

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top