← 中文资源

简体中文版本

用 array::map 变换定长数组

array::map 对定长数组整体映射:长度编译期固定、元素类型可换、不经过堆,与 Vec 的 iter+collect 路径形成对照。

阅读英文原文

实现说明

用 array::map 变换定长数组可以归结为函数 main。

使用要点

  • 每一步打印都带着自己的标签:calibrated:、flagged:、scaled:。

常见问题

运行「用 array::map 变换定长数组」会打印什么?

运行文件本身,calibrated:、flagged:、scaled: 这些前缀各对应一段演示逻辑。

核心语句

let scaled: Vec<u16> = raw_vec.iter().map(|s| s * 2).collect();
let calibrated: [f64; 4] = raw.map(|sample| sample as f64 / 1023.0);
let doubled: [u16; 4] = raw.map(|s| s.saturating_mul(2));

代码示例

fn main() {
    // a fixed-size sampling frame: raw readings for 4 channels
    let raw: [u16; 4] = [1000, 1023, 988, 1010];

    // array::map returns a new array: length fixed at compile time, element type free to change, and no heap involved
    let calibrated: [f64; 4] = raw.map(|sample| sample as f64 / 1023.0);
    println!("calibrated: {calibrated:?}");

    // each channel gets a limit check: the array transforms wholesale into a boolean array
    let flagged: [bool; 4] = raw.map(|s| s > 1020);
    println!("flagged:    {flagged:?}");

    // a Vec would need iter plus collect, and it would allocate on the heap
    let raw_vec: Vec<u16> = raw.to_vec();
    let scaled: Vec<u16> = raw_vec.iter().map(|s| s * 2).collect();
    println!("scaled:     {scaled:?}");

    // map cannot add or drop elements: the result length always equals the input
    let doubled: [u16; 4] = raw.map(|s| s.saturating_mul(2));
    println!("doubled:    {doubled:?}");
}