Safe Access with Vec::get()
Write a Rust function that uses Vec::get() to safely access an element at a given index. The get() method returns Option<&T> — Some(&value) if the index is within bounds, or None if the index is out of bounds. Unlike direct array indexing with [index] which panics on invalid access, get() never panics.
Vec::get() is part of Rust's commitment to safety. Direct indexing with the [] operator performs bounds checking at runtime and panics if the index is out of range. The get() method provides a safe alternative that returns None instead of panicking, allowing the caller to handle the missing case gracefully.
The get() method returns a reference to the element (&T), which borrows from the vector. The lifetime of the returned reference is tied to the vector's lifetime. The Option wrapper makes the possibility of missing data explicit in the type system, so the compiler ensures you handle both the Some and None cases.
Time complexity is O(1) as get() performs a bounds check followed by a pointer offset. Space complexity is O(1). The bounds check is a simple comparison between the index and the vector's length, making it as efficient as direct indexing.
Edge cases include empty vectors (any index returns None), index 0 on a non-empty vector (returns Some if vector length > 0), index equal to vector length (returns None since indices are 0-based), and very large indices beyond the vector's bounds.
Example Input & Output
Index 5 is out of bounds
Index 2 is the last element
Index 3 is out of bounds
Index 0 exists, returns Some
Empty vector, any index returns None
Algorithm Flow

Solution Approach
Best Answers
fn solution(nums: Vec<i32>, index: usize) -> Option<i32> {
nums.get(index).copied()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
