Where are we with const associated fns in Traits?

According to the tracking issue of const and Traits the reference is this discussion on Internals by @fee1-dead which states:

It was closed April 2022, for inactivity.

This is quite unsatisfying to me. The Store RFC actually needs to use this work-around:

  • Vec::new is (and should be) const, hence obtaining a dangling handle should be doable in a const context.
  • Allocating system memory in a const context is just NOT possible.

This leads to a split API:

trait StoreDangling {
    type Handle;

    fn dangling(&self) -> Self::Handle;

trait Store: StoreDangling {
    fn allocate(&self, ...) -> Result<...>;

    // snip

Which is downright painful, for both implementers and users.

I don't think there's any technical constraint here: the compiler already can invoke associated functions on traits in a const context, otherwise const trait implementations wouldn't work.

There's also an obviously regularity and ergonomic argument for accepting const associated functions in traits.

Would anyone know if there has been a change of position, RFC, etc... since then? And whether it's already planned, or could potentially be developed as part of the existing experiment anyway?


I have also been wondering about this lack. For one thing now that trait functions can be async, by symmetry and language consistency const should likewise be possible. This would give many new possibilities for creating statics. Though if static mut gets banned, only inner mutable ones would be useful.

One candidate I specially think about is Default::default(). I haven't checked, but I doubt this should ever do anything dynamic. If there is code that has it dynamic, then this function is screwed for const. Otherwise it could switch in edition 2024 (probably too late to initiate this change?)

Of course there is, e.g. in std you have Box, Rc, Arc. Even many std collections didn't have const constructors until recently; technically some still don't due to some allocator API hangup I didn't look into. And it's surely prolific in the wild, too.

More generally, it's a breaking change for any public trait to start requiring const. You need ~const or refinement or a subtrait or such.


As far as I know, everything related to const in traits became part of the more general "effects" initiative. I do not know the status of that.

I agree that "always const" functions in traits are the most obvious kind of const-fn-in-trait. I am not sure if there are any plans to implement that independent of the rest of the effect system (which should allow things like "an impl of Eq where all fn are const").

1 Like

For anyone wondering, there's actually a RFC on the topic: RFC: `const` functions in traits by tgross35 · Pull Request #3490 · rust-lang/rfcs · GitHub

Hasn't moved since October last year, though.