You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Rust中如何获取数组的常量长度?

如何在Rust中获取数组的编译期常量长度?

Rust数组的长度在编译期就是已知的,但我没法把它作为常量整数获取。虽然能通过数组切片的len()方法拿到长度,但这个值不是const的。Rust没有C++那样的begin/end迭代器,我也不确定能不能用字节长度除以元素字节大小来计算。我是Rust新手,找了好几天方法,知道可以克隆数组,但那只适用于克隆场景;遍历元素来统计长度又比直接从类型获取慢很多。Rust文档里数组的类型签名是[ele_type; ele_number],说明编译器肯定在跟踪这个长度,std::any::type_name::()能打印类型,但输出不是const值。

我知道有相关的旧问题,但现有回答解决不了我的问题,而且现在Rust版本更新了,情况可能有变化。

编辑1 添加示例代码:

fn main()
{
    let test_arr = [0.f64; 10];
    do_something(test_arr);
}

fn do_something<const C: usize>(array: [f64; C])
{
    // 报错:len()返回非const值,无法用于创建新数组;C被视为外部参数也无法使用
    let triple_size_array = [f64; array.len()*3];
}

编辑2:
直接写let array = [f64; C];是可行的,但没法用C做整数运算来定义不同大小的数组,只能直接用泛型参数:

13 | fn ftcs_update<const C: usize>(u: &[f64;C], f: fn(f64)->f64, l: f64)
   |                      - 外部函数的const参数
14 | {
15 |     const grid_size: usize = C;
   |                              ^ 使用外部泛型参数报错

error: aborting due to previous error

For more information about this error, try `rustc --explain E0401`.
error: generic parameters may not be used in const operations
  --> main.rs:16:22
   |
16 |     let u_new = [0.; C*3];
   |                      ^ 无法用`C`执行const运算
   |
   = help: const参数仅能作为独立参数使用

编辑3:
尝试了建议的方案,仍然报错:

error[E0401]: can't use generic parameters from outer function
  --> main.rs:15:30
   |
13 | fn ftcs_update<const C: usize>(u: &[f64;C], f: fn(f64)->f64, l: f64)
   |                      - 外部函数的const参数
14 | {
15 |     const grid_size: usize = C;
   |                              ^ 使用外部泛型参数报错

error: aborting due to previous error

For more information about this error, try `rustc --explain E0401`.

内容的提问来源于stack exchange,提问作者Liam Clink

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:54:48