Compile time const generic parameter check

Hello! I'm trying to bounds check a const generic type parameter at compile time for a particular function.
I'm able to convince rustc to do what I want, but I wonder if there are better alternatives.

struct Array<const SIZE: usize> {
    array: [u8; SIZE],

impl<const SIZE: usize> Array<SIZE> {
    const COMPTIME_SIZE_CHECK: () = assert!(SIZE > 0 && SIZE < 4);

    fn thing(self) -> u8 {
        // The following is more intuitive to me, but it gives
        // error[E0401]: can't use generic parameters from outer function
        // const _: () = assert!(SIZE > 0 && SIZE < 4);

        // Instead, we can do the check by referencing an associated constant
        let _ = Self::COMPTIME_SIZE_CHECK;

fn main() {
    // Time to monomorphisize.
    Array { array: [1, 2, 3, 4] }.thing(); // too large
    Array { array: [] }.thing(); // too small
    dbg!(Array { array: [42] }.thing()); // okay

Stable Rust is happy to evaluate the associated constant, but not happy if the exact same const item is put inside the function. This seems odd to me and I was wondering if there is a deeper reason to this constraint. Maybe it has to do with the timing at which constant expressions are evaluated?

I tried looking around for nightly features and compiler issues relating to this, but couldn't find anything about this particular oddity. The closest I got is learning that apparently the timing at which associated constants are evaluated is currently not stabilized.

Could you give me some pointers to satisfy my curiosity?

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.