std-method

slice::get

Check the bounds before borrowing an element or subrange. The result is Option, so missing data can be handled explicitly. Expected stdout (not executed): Some(24) None Some([24, 36]) Common mistake: Using indexing for user-supplied offsets without checking bounds.

Formal Syntax & Structure

rust syntaxrust
slice.get(index_or_range)

Working Example

Example Snippetrust
fn main() {    let data = [12, 24, 36];    println!("{:?} {:?}", data.get(1), data.get(4));    println!("{:?}", data.get(1..3));}
Rust Reference