liveBook · Manning

Indexing

As explained in Learn Rust in a Month of Lunches

Indexing selects elements in an ordered collection by their numeric positions.

Indexing means choosing an item by its position. In a Rust array, put the position in square brackets after the array name. Positions start at 0: `[0]` gets the first item, and `[1]` gets the second. section 3.1.1

Get one array item

With `let my_numbers = [0, 10, -20];`, `my_numbers[1]` gets `10`, the second item. Starting at 0 can feel unusual at first; just count the first item as position 0. section 3.1.1

You can also use positions to take a slice—a piece of an array. In `&array_of_ten[2..5]`, the `&` makes a reference to the piece, while `2..5` selects positions 2, 3, and 4. The end position is not included. Use `..=` when you want to include it. section 3.1.1

fn main() {
    let array_of_ten = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 
    let two_to_five = &array_of_ten[2..5];     #1
    let start_at_one = &array_of_ten[1..];     #2
    let end_at_five = &array_of_ten[..5];      #3
    let everything = &array_of_ten[..];        #4
 
    println!("Two to five: {two_to_five:?},
Start at one: {start_at_one:?},
End at five: {end_at_five:?},
Everything: {everything:?}");
}

Compare the four slices: a range with both endpoints, a range without a final endpoint, one without a starting endpoint, and the whole array. section 3.1.1

Rust uses `usize` for index numbers. An index cannot be negative, and `usize` provides a size suited to the computer running the program. section 1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through square-bracket indexing and slice ranges, but does not develop array operations beyond getting entries and slices.
Examples
Uses a three-number array to get its second item and a ten-number array to compare slice ranges.
What it assumes
Introduces positions from zero and explains slices as pieces of arrays; assumes familiarity with basic array notation.
What you can do after
Practice/perform array entry selection and create slices with exclusive or inclusive range endpoints.
How it connects
Connects indexing to arrays, slices, ranges, references, and `usize`.

Also explained in

Compare how 15 books explain indexing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.