Day 13g: Vector Safety and Error Handling
Introduction
Vectors are a core part of Rust's safe memory management, but you still need to handle edge cases and errors properly. In this session, we’ll cover safe element access using Option
, preventing out-of-bounds access, and handling scenarios like zero-length vectors.
Safe Element Access with get()
Accessing vector elements directly using indexing can cause runtime panics if the index is out of bounds. The safer method is to use get()
, which returns an Option
.
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
match numbers.get(10) {
Some(&num) => println!("Found: {}", num),
None => println!("Out of bounds!"),
}
}
Handling Out-of-Bounds Access
Using index-based access like numbers[10]
will panic if the index is out of bounds. Always prefer get()
when unsure of the index validity.
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
if let Some(&num) = numbers.get(10) {
println!("Number: {}", num);
} else {
println!("Index out of bounds");
}
}
Edge Cases with Empty and Resized Vectors
It’s essential to handle vectors that may be empty or resized dynamically. Using methods like is_empty()
and checking the length helps avoid issues.
fn main() {
let empty_vec: Vec<i32> = Vec::new();
if empty_vec.is_empty() {
println!("Vector is empty");
}
let mut numbers = vec![1, 2, 3, 4];
numbers.resize(2, 0);
println!("{:?}", numbers); // Output: [1, 2]
}
Conclusion
By using safe access methods and handling edge cases like empty vectors or resizing, you can prevent runtime panics and ensure that your code is resilient to errors.