Array From Fn Builds Lookup Tables

Fill a fixed-size array element by element with array::from_fn, getting an inline, stack-allocated table computed from each index at construction.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    // from_fn 按下标逐个构造元素:定长查找表一行写完,栈上分配
    let squares: [u32; 10] = std::array::from_fn(|i| (i as u32) * (i as u32));
    println!("squares: {squares:?}");

    // 与 Vec 不同:长度是类型的一部分,越界在编译期由索引检查兜住
    let hex_digit: [u8; 16] = std::array::from_fn(|i| {
        if i < 10 {
            b'0' + i as u8
        } else {
            b'a' + (i - 10) as u8
        }
    });
    println!("hex table: {}", String::from_utf8_lossy(&hex_digit));

    // 取表:查 13 的十六进制位
    let d = hex_digit[13] as char;
    println!("digit 13 -> {d}");
}

What the code does

Count the function main as the entire surface area of Array From Fn Builds Lookup Tables.

Applying it

The main signature reads fn main()

The demo output is labeled (squares:, hex table:, digit 13 ->), so every printed line maps back to its originating operation.

Statements that matter

let squares: [u32; 10] = std::array::from_fn(|i| (i as u32) * (i as u32));
let d = hex_digit[13] as char;
b'a' + (i - 10) as u8
}

Interactive Tools for This Topic

FAQ

What does Array From Fn Builds Lookup Tables print when run?
Invoke the file as-is — the `squares:`, `hex table:`, `digit 13 ->` prefixes identify which step printed each line.