Trait associated constants at type level

Say I have the following trait (a perversion of the dasp crate)

trait Frame {
    const NUM_CHANNELS: usize;
    type Channels: Iterator<Item = i16>;
    type AsFloat: Frame;

    fn channels(&self) -> Self::Channels;
    fn as_float(self) -> Self::AsFloat;

Is it possible to constrain the constant <AsFloat as Frame>::NUM_CHANNELS == Self::NUM_CHANNELS? NUM_CHANNELS would have to be an associated constant generic type rather than an associated const.

If it's possible but only with nightly, I'm still interested.

Do you mean like this? Or are you trying to avoid generics on the trait?

trait Frame<const NUM_CHANNELS: usize> {
    type Channels: Iterator<Item = i16>;
    type AsFloat: Frame<NUM_CHANNELS>;
1 Like

I don't know whether this will eventually be possible, but the closest I got is this error:

error: cannot constrain an associated constant to a value
 --> src/
4 |     type AsFloat: Frame<NUM_CHANNELS = { Self::NUM_CHANNELS }>;
  |                         ------------^^^----------------------
  |                         |              |
  |                         |              ...cannot be constrained to this value
  |                         this associated constant...
1 Like

Yes I'm trying to say the trait implementor chooses the size, not the trait consumer. (existential vs universal)

Yes I think at the moment associated constants can not be type-level constants. Whether they will be useable as type constants in the future I don't know. I don't think there is any reason in theory why they can't.

this is permitted with feature(generic_const_exprs) but it is incomplete and pretty ICE prone (edit: assoc const bounds are not yet implemented though, but you can accomplish a similar thing with the feature)

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.