What is ~const?
This is Option
's contains()
method signature:
pub const fn contains<U>(&self, x: &U) -> bool
where
U: ~const PartialEq<T>
What exactly is that ~const
?
Solution 1:
This is a new-ish experimental syntax for the const_trait_impl
feature.
Remember that the std library can use experimental features even in the stable channel.
Basically, this allows you to implement a trait full all const functions and use it in a const context. Something like this:
trait MyTrait {
fn foo(&self);
}
struct A;
impl const MyTrait for A {
fn foo(&self) { /* is is a const function! */}
}
struct B;
impl MyTrait for B {
fn foo(&self) { /* is is NOT a const function */}
}
const fn test<X>(x: &X)
where X: ~const MyTrait
{
x.foo();
}
Now a call to test(&A)
can be done in a const context while a call to test(&B)
cannot. Without the ~const
it would never be a const function:
static THE_A: () = test(&A); //ok
static THE_B: () = test(&B); //error: B does not implement MyTrait constly
In the case of the Option
implementation, Option::contains()
is const if the implementation of T as PartialEq
is const.