Today I Learned

hashrocket A Hashrocket project

Rust Array Access is Bound Checked at Runtime

Today I encountered a feature of Rust that I hadn't seen before— uses of array subscript notation ('array[n]') are checked at runtime to ensure they fit into the bounds of the array.

Here's a passing test I wrote to demonstrate:

// src/
#[should_panic(expected="index out of bounds: the len is 3 but the index is 5")]
fn array_access_is_bound_checked_at_runtime() {
    let elements = ["Wind", "Fire", "Water"];
    assert_eq!("Wind", elements[5]);

'Such errant access is the source of many bugs in other systems programming languages.' —The Rust Programming Language

More information:

See More #workflow TILs