我想使用一个函数来连接两个数组,声明如下:
fn concatenate<const COUNT1: usize, const COUNT2: usize>(a: [i32;COUNT1], b: [i32;COUNT2]) -> [i32;{COUNT1+COUNT2}];
问题在于返回类型。这是具体的错误:
error: generic parameters may not be used in const operations
--> src\main.rs:4:101
|
4 | fn concatenate<const COUNT1: usize, const COUNT2: usize>(a: [i32;COUNT1], b: [i32;COUNT2]) -> [i32;{COUNT1+COUNT2}] {
| ^^^^^^ cannot perform const operation using `COUNT1`
|
= help: const parameters may only be used as standalone arguments, i.e. `COUNT1`
这个函数似乎很容易单态化,我不明白为什么编译器不允许它。使用rust 书只说(两次)不允许,但没有解释原因:
Const parameters can be used anywhere a const item can be used, with the exception that when used in a type or array repeat expression, it must be standalone (as described below).
As a further restriction, const parameters may only appear as a standalone argument inside of a type or array repeat expression.
有谁知道这种模式是如何反对 rust 模型的,因为至少从我的角度来看,它绝对不是实现限制。如果有帮助,这是整个功能:
fn concatenate<const COUNT1: usize, const COUNT2: usize>(a: [i32;COUNT1], b: [i32;COUNT2]) -> [i32;{COUNT1+COUNT2}] {
let mut output = [0i32;{COUNT1+COUNT2}];
output.copy_from_slice(
&a.iter().chain(b.iter()).map(|&item| item).collect::<Vec<i32>>()
);
output
}
最佳答案
您需要启用 generic_const_exprs
功能,该功能目前仅在 nightly 中可用(rust 1.63
):
#![feature(generic_const_exprs)]
fn concatenate<const COUNT1: usize, const COUNT2: usize>(a: [i32;COUNT1], b: [i32;COUNT2]) -> [i32;{COUNT1+COUNT2}] {
let mut output = [0i32;{COUNT1+COUNT2}];
output.copy_from_slice(
&a.iter().chain(b.iter()).map(|&item| item).collect::<Vec<i32>>()
);
output
}
关于generics - 为什么 rust 只允许数组大小的独立常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72458782/