error[E0379]: functions in traits cannot be declared const
トレイトで const
関数を宣言した。
以下は const
文脈でよくある状況。
Add
などの四則演算トレイトが使えない。
これにより、Rust 標準にない複素数型のような型の計算ができない。
なお、標準の数値型についてはコンパイラが何とかしてくれる。
IntoIterator
などのトレイトが使えない。
これにより、for ループ構文が完全に使えなくなってしまう。
参考:『E0015 - const 文脈での非 const 関数 - for ループ』
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)
}
}