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

Rust中是否存在类似C99数组指定范围初始化器的语法?

Rust中const数组的范围初始化实现

C99支持通过数组指定器语法快速初始化数组的指定范围元素:

int a[10] = { [4 ... 8] = 10 };

在Rust中,非const环境下可以用fill()方法实现类似效果:

let mut a: [i32; 10] = [0; 10];
a[4..9].fill(10);

但fill()方法无法在const代码块中使用,以下是const环境下的可行方案:

方案1:const函数+编译期循环

通过const函数在编译期完成数组的范围初始化:

const fn create_initialized_array() -> [i32; 10] {
    let mut arr = [0; 10];
    let mut i = 4;
    // 对应C99中的[4...8],Rust区间为左闭右开,因此终止值设为9
    while i < 9 {
        arr[i] = 10;
        i += 1;
    }
    arr
}

// 定义const数组
const INITIALIZED_ARRAY: [i32; 10] = create_initialized_array();

方案2:内联const代码块(Rust 1.59+)

直接在const数组定义中嵌入编译期执行的代码块:

const INITIALIZED_ARRAY: [i32; 10] = {
    let mut arr = [0; 10];
    let mut idx = 4;
    while idx < 9 {
        arr[idx] = 10;
        idx += 1;
    }
    arr
};

以上两种方式都会在编译期完成数组初始化,生成的结果和C99的写法完全等效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 12:42:10