rust-lang / lang-team

Home of the Rust lang team

Home Page:http://lang-team.rust-lang.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Experiment: Generic const items

fmease opened this issue · comments

In the current version of Rust it is impossible to place generic parameters and where-clauses on free and associated constant items. This limits developers in their expressive power and renders certain desired functionality unattainable.

I hereby propose an experiment carried out by me in which the compiler gets extended to support generic const items addressing the aforementioned shortcoming of the language in an attempt to identify benefits and concerns in preparation for an RFC.

Motivation and use-cases

In no particular order:

  • It makes constant items more consistent with other similar items, those being type aliases, associated types, free & associated functions, ADTs, traits and implementations. This is especially true for associated constants whose two siblings both already support generic parameters and where-clauses.
  • It allows for increased conciseness. While generic parameters on free & associated constant items can (always?) be emulated by moving them up to the parent of the constant (i.e. the corresponding trait or type which may require defining such a parent beforehand and converting a free to an associated constant), this approach is cumbersome and unintuitive for both the author and the consumer. As for a concrete example, one does not have to look any further than the compiler itself: TyCtxtConsts::<'tcx>::DEREF_PROJECTION (example kindly provided by @compiler-errors)
  • It enables users to write const-evaluatable bounds (currently part of the feature generic_const_exprs) on constant items unblocking many useful patterns. See also rust-lang/rust#104400.
  • It could form the basis for a potential MVP of generic_const_exprs. See also https://lcnr.de/blog/generic-const-expressions/
  • It allows users to make their traits that contain associated constants object-safe by adding where Self: Sized to each associated constant just like they would do with associated functions and types. See also rust-lang/rust#112319.

Links

Initial people involved

As before, I'm happy to second/liason an experiment for this. We already have None::<i32> that sure looks like a generic const, so experimenting with a "real" version of that makes good sense to me.

cc @rust-lang/lang in case anyone wants to raise an objection.

@fmease We briefly raised this in the lang team meeting today, and there were still no objections, so the experiment is approved to move forward!