Search code examples
genericsrusttraits

A trait that represents types that can be tuple constructed


I have the following code, with my bogus TupleConstructor trait:

pub trait Axis {
    const MIN: Self;
    const MAX: Self;
}

pub trait AxisU64: TupleConstructor<u64> {}

impl<T: AxisU64> Axis for T {
    const MIN = Self(u64::MIN);
    const MAX = Self(u64::MAX);
}

pub struct XAxis(u64);
impl AxisU64 for XAxis {}

pub struct YAxis(u64);
impl AxisU64 for YAxis {}

Essentially, I want to have constants for each object that implements the Axis trait, but I don't know if there's a syntax for this. All of this information should be available at compile-time through generics instantiation.

An alternative is to use from or into, but that is not a const fn and I can't make them constants.


Solution

  • There is no way to generically get a tuple struct's constructor from the type. Tuple structs do not gain any characteristics such as trait implementations due to being tuple structs. (Also, even if there was a TupleConstructor trait, it would only be available for tuple structs with public fields, and you wouldn't be able to use it to define constants because trait functions can't currently be called from const evaluation.)

    However, you could write a derive macro (perhaps with the help of macro_rules_attribute since it's a simple pattern) that generates Axis implementations with the two constants.