简体   繁体   English

Rust 常量表达式依赖于一个泛型参数

[英]Rust constant expression depends on a generic parameter

I'm trying to generalize some algebraic operations in Rust (like for groups, rings, fields, etc), and I ran into this problem trying to implement the cross product of two "sets" (Vec's).我试图概括 Rust 中的一些代数运算(如组、环、字段等),我在尝试实现两个“集合”(Vec)的叉积时遇到了这个问题。

(Note that this is using const_generics in the nightly toolchain.) (请注意,这是在夜间工具链中使用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
}

Wherever I have the expression [T;N+M] , I get an error that says constant expression depends on a generic parameter , which makes no sense.无论哪里有表达式[T;N+M] ,我都会收到一个错误,指出常量表达式取决于泛型参数,这是没有意义的。

Your code does actually compile on the latest nightly , all you need is a couple of feature flags.您的代码实际上是在最新的 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));
}

And when trying to compile with just #![feature(min_const_generics)] , compiler actually recommends this solution:当尝试仅使用#![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