error: generic parameters may not be used in const operations

定数式でジェネリクス定数を使った計算が行われた。

原因

これはの Rust の制限である。

歴史を追うと、Rust 1.51 (2021-03-25) で機能 min_const_generics が導入されて以降、ジェネリクス定数についての機能は少しずつ拡充してきている。そして、現在はまだいくつかの重要な機能が足りていない。

不安定な機能 generic_const_exprs ではこの問題を解決しようとしている。しかし、この機能はまだ開発途中のため、ナイトリー版でも試用に注意が必要となる。

サンプル


fn main() {
    let mut dst = [0; 5];
    merge_to(&mut dst, &[1, 2], &[3, 4, 5]);
    assert_eq!(dst, [1, 2, 3, 4, 5]);
}

fn merge_to<const M: usize, const N: usize>(
	dst: &mut [i32; M + N],
    src1: &[i32; M],
    src2: &[i32; N],
) {
    dst[0..M].copy_from_slice(src1);
    dst[M..M + N].copy_from_slice(src2);
}

error: generic parameters may not be used in const operations
 --> src\main.rs:8:21
  |
8 |     dst: &mut [i32; M + N],
  |                     ^ cannot perform const operation using `M`
  |
  = help: const parameters may only be used as standalone arguments, i.e. `M`

error: generic parameters may not be used in const operations
 --> src\main.rs:8:25
  |
8 |     dst: &mut [i32; M + N],
  |                         ^ cannot perform const operation using `N`
  |
  = help: const parameters may only be used as standalone arguments, i.e. `N`