Final associated constants?

Tracking issue for RFC 3678: Trait method impl restrictions (`final` methods) · Issue #131179 · rust-lang/rust · GitHub is about final methods, but I think it might be equally valuable for associated constants.

For example, I currently have a piece of code that looks like this (nightly, not sure if it works on stable):

pub trait InstructionIsa<Cfg>: Instruction {
    // ...

    const ISA_STRING: &'static str = const {
        isa_string(
            Self::Reg::XLEN,
            &InheritedIsa::new::<Self, Cfg>(),
            Self::IMPLEMENTED_EXTENSIONS,
        )
    }
    .unsize()
    .as_str();

And I'm not sure I want implementers to be able to override its implementation, but I can only avoid that if I convert it to a method, which is unfortunate.

So the question is: should final associated constants be a thing too?

3 Likes

A simpler example would be something like this:

pub const trait VectorRegisters {
    type Hart: HartConfig;

    // ...
}

pub const trait VectorRegistersExt {
    final const ELEN: Elen = Self::Hart::ELEN;
    final const VLEN: Vlen = Self::Hart::VLEN;

    // ...
}

Here ELEN and VLEN are just helpers that reduce verbosity of the code elsewhere, but they must be strictly the same as inside Self::Isa. Without final implementers of these traits can override them and cause divergence.

There is currently final fn allowed inside traits on nightly. I imagine a PR expanding that to any trait item would be viewed favorable.

2 Likes