Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bound contraint for trait associated const #3095

Open
Evian-Zhang opened this issue Mar 13, 2021 · 2 comments
Open

Add bound contraint for trait associated const #3095

Evian-Zhang opened this issue Mar 13, 2021 · 2 comments

Comments

@Evian-Zhang
Copy link

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?

@lqf96
Copy link

lqf96 commented Mar 22, 2021

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).

@Xiretza
Copy link

Xiretza commented Jun 26, 2022

See also #3162.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants