Introduction
Accessing elements lets you get specific items from a list or collection. It helps you work with data one piece at a time.
Accessing elements lets you get specific items from a list or collection. It helps you work with data one piece at a time.
let element = collection[index];
Index starts at 0, so the first element is at index 0.
Rust checks if the index is valid and will panic if it is out of range.
let numbers = [10, 20, 30]; let first = numbers[0];
let chars = ['a', 'b', 'c']; let second = chars[1];
let words = vec!["hello", "world"]; let word = &words[1];
This program prints each fruit by accessing elements at index 0, 1, and 2.
fn main() {
let fruits = ["apple", "banana", "cherry"];
println!("First fruit: {}", fruits[0]);
println!("Second fruit: {}", fruits[1]);
println!("Third fruit: {}", fruits[2]);
}Using an index outside the collection size causes a runtime panic.
For safe access, you can use the get() method which returns an Option.
Access elements by using square brackets and an index.
Indexing starts at zero.
Rust checks index bounds and panics if invalid.
arr?arr[0] accesses the first element directly.v in Rust?v[2] to access the third element.let arr = [10, 20, 30, 40];
println!("{}", arr[1]);arr has elements: 10 at index 0, 20 at index 1, 30 at index 2, and 40 at index 3.arr[1], which is 20.let v = vec![1, 2, 3]; let x = v[3];
v has 3 elements at indexes 0, 1, and 2. Index 3 is out of range.v[3] causes a panic at runtime due to index out of bounds.let data = vec![vec![1, 2], vec![3, 4], vec![5, 6]];. How do you access the number 4?Pass the test and this pattern moves unknown