簡體   English   中英

Rust 常量表達式依賴於一個泛型參數

[英]Rust constant expression depends on a generic parameter

我試圖概括 Rust 中的一些代數運算(如組、環、字段等),我在嘗試實現兩個“集合”(Vec)的叉積時遇到了這個問題。

(請注意,這是在夜間工具鏈中使用const_generics 。)

fn CrossProduct<T, const N: usize, const M: usize>(lhs: Vec<[T;N]>, rhs: Vec<[T;M]>) -> Vec<[T;N+M]> {
    let mut out: Vec<[T;N+M]> = Vec::with_capacity(lhs.len() * rhs.len());

    for i in 0..lhs.len() {
        for j in 0..rhs.len() {
            let mut inner: [T; N+M] = [lhs[i][0]; N+M];
            for idx in 1..N {
                inner[idx] = lhs[i][idx];
            }
            for idx in 0..M {
                inner[idx + N] = rhs[j][idx];
            }
            out.push(inner);
        }
    }
    out
}

無論哪里有表達式[T;N+M] ,我都會收到一個錯誤,指出常量表達式取決於泛型參數,這是沒有意義的。

您的代碼實際上是在最新的 nightly 上編譯的,您所需要的只是幾個功能標志。

#![feature(const_generics)]
#![feature(const_evaluatable_checked)]
fn CrossProduct<T: Copy, const N: usize, const M: usize>(lhs: Vec<[T;N]>, rhs: Vec<[T;M]>) -> Vec<[T;N+M]> {
    let mut out: Vec<[T;N+M]> = Vec::with_capacity(lhs.len() * rhs.len());

    for i in 0..lhs.len() {
        for j in 0..rhs.len() {
            let mut inner: [T; N+M] = [lhs[i][0]; N+M];
            for idx in 1..N {
                inner[idx] = lhs[i][idx];
            }
            for idx in 0..M {
                inner[idx + N] = rhs[j][idx];
            }
            out.push(inner);
        }
    }
    out
}

fn main() {
    let a = vec![[1i32,2,3],[1,2,3],[1,2,3]];
    let b = vec![[1,2,3],[1,2,3],[1,2,3]];
    println!("{:?}", CrossProduct(a, b));
}

當嘗試僅使用#![feature(min_const_generics)]進行編譯時,編譯器實際上推薦了這個解決方案:

error: generic parameters may not be used in const operations
 --> src/main.rs:2:102
  |
2 | fn CrossProduct<T: Copy, const N: usize, const M: usize>(lhs: Vec<[T;N]>, rhs: Vec<[T;M]>) -> Vec<[T;N+M]> {
  |                                                                                                      ^ cannot perform const operation using `N`
  |
  = help: const parameters may only be used as standalone arguments, i.e. `N`
  = help: use `#![feature(const_generics)]` and `#![feature(const_evaluatable_checked)]` to allow generic const expressions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM