rfcs
rfcs copied to clipboard
Add bound contraint for trait associated const
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?
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).
See also #3162.