expression

Index a flat row-major matrix safely

In row-major contiguous storage, each row occupies adjacent elements. The stride between rows equals the column count in elements. Validate both coordinates before computing a checked offset; a linear index alone cannot detect an out-of-range column that spills into the next row. Expected result (NOT RUN): value: Some(60), invalid: None Common mistake: Using r * cols + c without checking each axis. Static Rust example; not a verified ByteMind executable assessment.

Formal Syntax & Structure

rust syntaxrust
row.checked_mul(cols)?.checked_add(col)?

Working Example

Example Snippetrust
fn get(data: &[i32], rows: usize, cols: usize, r: usize, c: usize) -> Option<i32> {    if r >= rows || c >= cols || rows.checked_mul(cols)? != data.len() { return None; }    data.get(r.checked_mul(cols)?.checked_add(c)?).copied()}fn main() {    let data = [10, 20, 30, 40, 50, 60];    println!("value: {:?}, invalid: {:?}", get(&data, 2, 3, 1, 2), get(&data, 2, 3, 0, 3));}
Rust Reference