Code Logo

Safe Access with Vec::get()

Published at25 Jul 2026
Rust Data Structures Easy 0 views
Like0

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

Example 1
Input
[10,20,30],5
Output
None
Explanation

Index 5 is out of bounds

Example 2
Input
[10,20,30],2
Output
Some(30)
Explanation

Index 2 is the last element

Example 3
Input
[10,20,30],3
Output
None
Explanation

Index 3 is out of bounds

Example 4
Input
[10,20,30],0
Output
Some(10)
Explanation

Index 0 exists, returns Some

Example 5
Input
[],0
Output
None
Explanation

Empty vector, any index returns None

Algorithm Flow

Recommendation Algorithm Flow for Safe Access with Vec::get()
Recommendation Algorithm Flow for Safe Access with Vec::get()

Solution Approach

fn solution(nums: Vec<i32>, index: usize) -> Option<i32> {
    nums.get(index).copied()
}

Best Answers

rust - Approach 1
fn solution(nums: Vec<i32>, index: usize) -> Option<i32> {
    nums.get(index).copied()
}