error[E0379]: functions in traits cannot be declared const

トレイトで const 関数を宣言した。

影響

以下は const 文脈でよくある状況。

サンプル


fn main() {
    const FLAG: bool = MyType(1).is_ok();
    assert!(FLAG);
}

trait Flag {
    const fn is_ok(&self) -> bool;
}

struct MyType(i32);
impl Flag for MyType {
    const fn is_ok(&self) -> bool {
        self.0 != 0
    }
}

error[E0379]: functions in traits cannot be declared const
 --> src/main.rs:7:5
  |
7 |     const fn is_ok(&self) -> bool;
  |     ^^^^^-
  |     |
  |     functions in traits cannot be const
  |     help: remove the `const`

error[E0379]: functions in trait impls cannot be declared const
  --> src/main.rs:12:5
   |
12 |     const fn is_ok(&self) -> bool {
   |     ^^^^^-
   |     |
   |     functions in trait impls cannot be const
   |     help: remove the `const`

error[E0015]: cannot call non-const fn `<MyType as Flag>::is_ok` in constants
 --> src/main.rs:2:34
  |
2 |     const FLAG: bool = MyType(1).is_ok();
  |                                  ^^^^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants

不安定な機能

不安定な機能 const_trait_impl はトレイトでも const 関数を使えるようにする。

サンプル - 基本形


#![feature(const_trait_impl)]

fn main() {
    const FLAG: bool = MyType(1).is_ok();
    assert!(FLAG);
}

#[const_trait]
trait Flag {
    fn is_ok(&self) -> bool;
}

struct MyType(i32);
impl const Flag for MyType {
    fn is_ok(&self) -> bool {
        self.0 != 0
    }
}

サンプル - 四則演算


#![feature(const_trait_impl)]
#![feature(const_ops)]

use std::ops::Add;

fn main() {
    const NUM: MyNum = MyNum(1) + MyNum(2);
    assert_eq!(NUM.0, 3);
}

struct MyNum(i32);

impl const Add for MyNum {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}