常量泛型

版本新特性 / Rust 1.51

// *** before: ***
// an array length was no type parameter, so code went through a slice
// and lost it from the type - or was multiplied by a macro
fn sum(values: &[i32]) -> i32 {
    values.iter().sum()
}

// *** in version 1.51: ***
// the length is an ordinary type parameter, known at compile time
fn sum<const N: usize>(values: [i32; N]) -> i32 {
    values.iter().sum()
}

struct Matrix<const ROWS: usize, const COLS: usize> {
    cells: [[f64; COLS]; ROWS],
}

println!("{}", sum([1, 2, 3]));