Reputation: 21971
Let's say I have this vector:
let mut v = vec![1,2,3];
And I want to remove some item from it:
v.remove(3);
It panics. How can I catch/gracefully handle that panic? I tried to use panic::catch_unwind
but it doesn't seem to work with vectors (std::vec::Vec<i32> may not be safely transferred across an unwind boundary
). Should I manually check if item exists at an index before removing it?
Upvotes: 1
Views: 3943
Reputation: 602715
In general, vector and slice methods consider it a programming error if they receive an index that is out of range, and the convention in Rust is to panic for programming errors. If your code panics, you generally need to fix the code to uphold the invariant that was disregarded.
Some of the slice methods have variants that don't panic for invalid indices. One example is the indexing operator [index]
, which panics for and out-of-bounds index, and the get()
method, which returns None
if the index is out of bounds.
The remove()
method does not have an equivalent that does not panic. You should check the index manually before passing it in:
if (index < v.len()) {
v.remove(index);
} else {
// Handle error
}
In real applications, this should rarely be necessary, though. The code that generates the index to be deleted can usually be written in a way that it will only yield in-bounds indices.
Upvotes: 8