Skip to content

MVP of associated constants for const generics #54

Open
@programmerjake

Description

@programmerjake

What is this

This is a design document for const generics. Any discussions about its content should be on zulip. The conclusions of these discussions should then be edited back into this issue. Please do not post any comments directly in this issue.

Content

originally on Rust Internals

I think it may be a good idea to have a MVP for allowing associated constants to be used in const generics, basically we'd introduce a attribute #[usable_in_const_generic] (to be bikesheded) where all associated constants decorated with that attribute are restricted such that they're usable in const generics:

pub trait MyTrait {
    #[usable_in_const_generic]
    const C: usize;
}

pub struct S<const C: usize>;

impl<const C: usize> S<C> {
    #[usable_in_const_generic]
    pub const C2: usize = C; // works since C can be used in a const generic
}

impl<const C: usize> MyTrait for S<C> {
    const C: usize = C; // works since C can be used in a const generic
    // const C: usize = C + 1; // doesn't work without `#![feature(generic_const_exprs)]`
}

pub struct S2<T: MyTrait>([u8; T::C]); // works, since C has #[usable_in_const_generic]
pub struct S3<T: MyTrait>([u8; T::C2]); // works, since C2 also has #[usable_in_const_generic]

the idea is that #[usable_in_const_generic] would be stabilized to allow much more ergonomic use of const generics with associated consts rather than having to use an associated type C = Const<42> instead of const C: usize = 42.

If at some later point const generics no longer need to be restricted (which seems doubtful considering the lack of even theoretical progress on generic_const_exprs in years), then usable_in_const_generic would become a no-op and be (soft-?)deprecated and removed from the next edition.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-design-docsCategory: This is part of our design documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions