Accessing Vector Elements
Part of the Logic & Flow section of Coddy's Rust journey — lesson 10 of 66.
Once you have a vector with elements, you'll need to access individual values. Rust provides two different approaches for getting elements from a vector, each with its own trade-offs between convenience and safety.
The first method uses index syntax with square brackets, similar to arrays:
let numbers = vec![10, 20, 30, 40];
let first = numbers[0]; // gets 10
let third = numbers[2]; // gets 30While this syntax is familiar and concise, it has a significant risk: if you try to access an index that doesn't exist, your program will panic and crash:
let numbers = vec![10, 20, 30];
let invalid = numbers[5]; // This will panic!The second method uses the .get() method, which provides safe access:
let numbers = vec![10, 20, 30, 40];
let first = numbers.get(0); // returns Some(10)
let invalid = numbers.get(5); // returns NoneThe .get() method returns an Option - either Some(value) if the index exists, or None if it doesn't. This forces you to handle the possibility that the element might not exist, preventing crashes and making your code more robust.
Challenge
EasyWrite a function get_element_at that takes a vector numbers and an index idx, and returns the element at that index using safe access.
Use the .get() method to safely access the element. If the index exists, return the value. If the index doesn't exist, return -1 as a default value.
Parameters:
numbers(Vec<i32>): The vector to accessidx(i32): The index to retrieve
Returns: The element at the given index, or -1 if the index doesn't exist (i32)
Cheat sheet
Rust provides two methods for accessing vector elements:
Index syntax with square brackets:
let numbers = vec![10, 20, 30, 40];
let first = numbers[0]; // gets 10
let third = numbers[2]; // gets 30This method will panic if the index doesn't exist:
let invalid = numbers[5]; // This will panic!The .get() method for safe access:
let numbers = vec![10, 20, 30, 40];
let first = numbers.get(0); // returns Some(10)
let invalid = numbers.get(5); // returns NoneThe .get() method returns an Option type - either Some(value) if the index exists, or None if it doesn't. This prevents crashes and requires explicit handling of missing elements.
Try it yourself
fn get_element_at(numbers: Vec<i32>, idx: i32) -> i32 {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together