How to seal the const generic?

Would something like this work?

pub struct Decimal<const BYTE_LENGTH: usize> {
    digits: [u8; BYTE_LENGTH],
}

impl<const BYTE_LENGTH: usize> Decimal<BYTE_LENGTH> {
    pub const fn new(digits: [u8; BYTE_LENGTH]) -> Self
    where
        Decimal<BYTE_LENGTH>: sealed::ValidByteLength,
    {
        Decimal { digits }
    }
}

pub trait ValidByteLength {}

impl ValidByteLength for Decimal<16> {}
impl ValidByteLength for Decimal<32> {}

(playground)

You don't need to make this a "sealed" trait because downstream users aren't allowed to implement ValidByteLength for Decimal<N>.

2 Likes