Why cant an enum be used as a Generic Constant?

โš“ Rust    ๐Ÿ“… 2025-10-03    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 7      

surdeus

Iโ€™m writing some generic math code to experiment with deterministic algorithms. The main things I want to do are:

  1. Specify the Storage Type, Scaling Type, Prefix and Units,
  2. Retain a maximum storage size for the struct as the same size of Storage Type,
  3. 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:

  1. 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?)
  2. 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

Read full topic

๐Ÿท๏ธ Rust_feed