什么是~const?

at5*_*321 6 rust

这是Optioncontains()方法签名:

pub const fn contains<U>(&self, x: &U) -> bool
where
    U: ~const PartialEq<T>
Run Code Online (Sandbox Code Playgroud)

那到底是什么~const

rod*_*igo 6

这是该功能的一种新的实验性语法const_trait_impl

请记住,即使在稳定通道中,std 库也可以使用实验性功能。

基本上,这允许您实现一个包含所有 const 函数的特征,并在 const 上下文中使用它。像这样的东西:

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();
}
Run Code Online (Sandbox Code Playgroud)

现在,对 的调用test(&A)可以在 const 上下文中完成,而对 的调用则test(&B)不能。如果没有它,~const它永远不会是一个 const 函数:

static THE_A: () = test(&A); //ok
static THE_B: () = test(&B); //error: B does not implement MyTrait constly
Run Code Online (Sandbox Code Playgroud)

在实现的情况下OptionOption::contains()如果 的实现是 const,则也是T as PartialEqconst。