Skip to content

Experiment: Generic const items #214

Closed
@fmease

Description

@fmease

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 no place to add evaluatable bounds to assoc const items 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 Don't require associated types with Self: Sized bounds in dyn Trait objects rust#112319.

Links

Initial people involved

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions