Why cant an enum be used as a Generic Constant?
โ Rust ๐ 2025-10-03 ๐ค surdeus ๐๏ธ 7Iโm writing some generic math code to experiment with deterministic algorithms. The main things I want to do are:
- Specify the Storage Type, Scaling Type, Prefix and Units,
- Retain a maximum storage size for the struct as the same size of Storage Type,
- Use static dispatch only.
The interface I want is:
Angle<i16, f32, Prefix::Micro, AngularUnit::Gradians>
Unfortunately it seems you cant use enums as constants for generic arguments. The closes I can get is:
Angle<i16, f32, { Prefix::Micro as i8 }, { AngularUnit::Gradians as i8 }>
The following size test is must (and does) pass:
assert_eq!(size_of::<Angle<i16, f32, { Prefix::Micro as i8 }, { AngularUnit::Gradians as i8 }>>(), 2 );
The important bits of the implementation looks like this:
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Angle<
StorageType: Number,
ScalingType: Float,
const STORAGE_PREFIX: i8,
const STORAGE_UNIT: i8,
> {
value: StorageType,
scalar: PhantomData<ScalingType>,
}
impl<
StorageType: Number,
ScalingType: Float + From<f32> + From<StorageType> + Into<StorageType>,
const STORAGE_PREFIX: i8,
const STORAGE_UNIT: i8,
> Angle<StorageType, ScalingType, STORAGE_PREFIX, STORAGE_UNIT>
{
pub fn new<InitType: Number + Into<StorageType> + Into<ScalingType>>(
value: InitType, prefix: Prefix, unit: AngularUnit,
) -> Self {
if prefix == Prefix::from(STORAGE_PREFIX) && unit == AngularUnit::from(STORAGE_UNIT) {
Self { value: value.into(), scalar: PhantomData }
} else {
let p = prefix.into();
let s = Prefix::from(STORAGE_PREFIX).into();
let v: ScalingType = value.into();
let v = Self::convert_units(v * p, unit, AngularUnit::from(STORAGE_UNIT)) * s;
Self { value: v.into(), scalar: PhantomData }
}
}
}
My questions are this:
- Why are enumโs no allowed as constants value for generics? (I.e. is there a language design reason for this, or just that it has not been developed yet?)
- Is there a better way to pass the STORAGE_PREFIX and STORAGE_UNIT that presents a cleaner interface to the users?
3 posts - 3 participants
๐ท๏ธ Rust_feed