rfcs icon indicating copy to clipboard operation
rfcs copied to clipboard

Add bound contraint for trait associated const

Open Evian-Zhang opened this issue 3 years ago • 2 comments

I recently post on rust forum about how to write constraint on associated const, and find out that there is no direct way to achieve this (even no RFC?).

For example, I have the following trait:

trait Foo {
    const FOO: usize;
}

And I want to have constraint for that like

fn foo<T: Foo>() where <T as Foo>::FOO < 4 {}

impl<T: Foo> SomeTrait for T where <T as Foo>::FOO.is_power_of_two() {}

const fn something_about_foo(foo: usize) -> bool { /* ... */ }
struct Bar<T: Foo> where something_about_foo(<T as Foo>::FOO) {}

Since we already have various mature bound constraint on associated type, there should be some bound constraint on associated const as well.

I also wonder how to design the syntax of associated const bound, since allowing any const expression in where clause may lead to hard parsing. Maybe a brace should be required?

Evian-Zhang avatar Mar 13 '21 01:03 Evian-Zhang

This is already possible in Nightly Rust today, by using const_generics and const_evaluatable_checked features as well as something analogous to C++'s std::conditional:

#![feature(const_generics)]
#![feature(const_evaluatable_checked)]

trait Satisfied {}

struct Cond<const PRED: bool>;

impl Satisfied for Cond<true> {}

trait Foo {
    const FOO: usize;
}

struct TestFoo;

impl Foo for TestFoo {
    const FOO: usize = 3;
}

fn foo<T: Foo>() where Cond<{<T as Foo>::FOO < 4}>: Satisfied {}

fn main() {
    foo::<TestFoo>();
}

But I agree there should be a more terse syntax for const constraints (a.k.a. refinements).

lqf96 avatar Mar 22 '21 08:03 lqf96

See also #3162.

Xiretza avatar Jun 26 '22 09:06 Xiretza